This question already has answers here:
Early exit from function?
(12 answers)
Closed 7 years ago.
I have the following:
function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
...
...
I would like to exit from this function if an "if" condition is met. How can I exit? Can I just say break, exit or return?
if ( condition ) {
return;
}
The return exits the function returning undefined.
The exit statement doesn't exist in javascript.
The break statement allows you to exit a loop, not a function. For example:
var i = 0;
while ( i < 10 ) {
i++;
if ( i === 5 ) {
break;
}
}
This also works with the for and the switch loops.
Use return statement anywhere you want to exit from function.
if(somecondtion)
return;
if(somecondtion)
return false;
you can use
return false; or return; within your condition.
function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
....
if(some_condition) {
return false;
}
}
Use this when if satisfies
do
return true;
You should use return as in:
function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
if (exit) {
return;
}
I had the same problem in Google App Scripts, and solved it like the rest said, but with a little more..
function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
if (condition) {
return Browser.msgBox("something");
}
}
This way you not only exit the function, but show a message saying why it stopped. Hope it helps.
Related
This question already has answers here:
forEach/for...in not returning values? [duplicate]
(5 answers)
Closed 5 years ago.
I've checked other questions that seem to be duplicates but none of them have solved my problem. I have this simple function that loops through an array of rule objects and returns the one with the matching "type":
$ctrl.findRule = function(ruleName){
$ctrl.rules.forEach(function(rule){
if(rule.type === ruleName){
console.log("returning rule: " + rule.type);
return rule;
}
});
return null;
};
I call this function as follows:
var wordCountRule = $ctrl.findRule("word_count");
console.log(wordCountRule);
I see on the console returning rule: word_count and then the console.log(wordCountRule) displays undefined. I have tried everything and I have no idea why this is happening.
Thanks!
The issue is because you're returning the value from the inner forEach handler function, not your outer findRule() function.
To fix this you could define a variable to hold the return value and amend that within the inner scope:
$ctrl.findRule = function(ruleName) {
var returnVal = null;
$ctrl.rules.forEach(function(rule) {
if (rule.type === ruleName) {
returnVal = rule;
}
});
return returnVal;
};
However you should note that it you're looking for a single value you can use find() directly, without the need to loop explicitly:
$ctrl.findRule = function(ruleName) {
return $ctrl.rules.find(function(rule) {
return rule.type === ruleName;
});
};
Taking the above example a step further, by using ES6 syntax it can be reduced to just this:
$ctrl.findRule = ruleName => $ctrl.rules.find(rule => rule.type === ruleName);
This question already has answers here:
Function in JavaScript that can be called only once
(32 answers)
Closed 6 years ago.
Execute function only one time in Javascript, no matter how many times it has been called.
I write the following code, but does not working.
var counter = 0;
if(n.data === YT.PlayerState.BUFFERING) {
setTimeout(function() {
if(counter===0) {
r.frontPlayer.seekTo(10);
counter++;
}}, 2000);
}
Try not to use timeouts, they invite misery and suffering. This is a simple example, I use jquery for attaching the events but the function is independent of jquery. The key thing is using the object, the anonymous function in this case, to track state.
<button id="testButton">
test
</button>
$("#testButton").click(function() {
if (null == this.ran) {
console.log("do something");
this.ran = true;
}
})
Take a look at underscore or lodash's _.once function:
var fn = _.once(function() {
console.log('this will only run once');
});
Or writing it yourself:
var fn = (function() {
var called = false;
var ret;
return function() {
if (called) return ret;
called = true;
// do stuff
// ..
ret = 'some return value';
return ret;
};
})();
This question already has answers here:
What does `return` keyword mean inside `forEach` function? [duplicate]
(2 answers)
Closed 2 years ago.
I am trying to determine whether or not an array holds a certain item. If it does, I would like to hold the function, otherwise it should get added.
function addPacking(item){
data.packings.forEach(function(entry){
if(item.name == entry.name){
return;
}
});
data.packings.push(item);
}
Unfortunately, the data is pushed even when the if condition is met. How do I prevent this behaviour without using an else condition?
(I do not want to use else because my actual code is a lot more complex than this and I'd like to keep it readable)
Edit:
Does forEach execute asynchronously?
Old ways are sometimes the best. It's because you're passing a delegate function when calling .forEach. The return within the delegate is getting lost, and isn't applying to anything. To get your desired result, you'll want to exit the calling function addPacking. This can be done using a simply for loop.
function addPacking(item){
for (var i = 0; i < data.packings.length++; i++) {
if (item.name == data.packings[i].name) {
return;
}
}
data.packings.push(item);
});
This approach also supports older browsers, unlike some, every and forEach
You can't stop forEach execution other than throwing an exception (#Yoshi). Which should not be considered as an option to affect program code flow (#Me).
What you can do is to use another method some or every
function addPacking(item){
var contains = data.packings.every(function(entry){
return item.name != entry.name;
});
if(contains) {
data.packings.push(item);
}
}
Or
function addPacking(item){
var conatins = !data.packings.some(function(entry){
return item.name == entry.name;
});
if(contains) {
data.packings.push(item);
}
}
OLD question but in case someone else comes across this thread.
If you are using ECMAScript 6 you can use the Array find() method
var found = myArray.find(function (element) { return element === arrayToFind; });
so for this particular scenario would be:
function addPacking(item){
var foundItem = data.find(function(entry){ return entry.name == item.name});
if (foundItem) data.packings.push(foundItem);
}
see http://www.w3schools.com/jsref/jsref_find.asp for another worked example.
Return just aborts the function called in forEach, not your addPackings function.
function addPacking(item){
var isInPackings = false;
data.packings.forEach(function(entry){
if(item.name == entry.name){
isInPackings = true;
}
});
if (!isInPackings)
data.packings.push(item);
}
Yo are just returning from the child function but not from the parent function
function addPacking(item){
var check=false;
data.packings.forEach(function(entry){
if(item.name == entry.name){
check=true;
return;
}
});
if (check) return;
data.packings.push(item);
}
This question already has answers here:
Implementing a 'once' function in JavaScript
(3 answers)
Closed 8 years ago.
I have a code below,
var a = 0;
var addByOne = doOnce(function() { a += 1; });
// I need to define a doOnce function here
// Run addByOne two times
addByOne();
addByOne();
This will result the variable a holds 2 as its value. My question is, how do I make the doOnce function so that it will result in running the function inside doOnce (in the case above, function () { a += 1; } ) just one time. So no matter how many times addByOne is called, variable a will be incremented just once.
Thanks
This can be achieved by creating a doOnce function which returns a wrapper for calling the passed function if it has not already been run. This may look something like this;
doOnce = function(fn) {
var hasRun = false,
result;
return function() {
if (hasRun === false) {
result = fn.apply(this, arguments);
hasRun = true;
}
return result;
}
}
Try this:
function doOnce(fn) {
// Keep track of whether the function has already been called
var hasBeenCalled = false;
// Returns a new function
return function() {
// If it has already been called, no need to call it again
// Return (undefined)
if (hasBeenCalled) return;
// Set hasBeenCalled to true
hasBeenCalled = true;
return fn.apply(this, arguments);
}
}
If you want, you can keep track of the return value and return that instead of undefined.
This question already has answers here:
Jquery .each() - return value undefined
(3 answers)
Closed 9 years ago.
Why the does following Javascript function return "undefined" in alert.
here is the snipptet
var tests = validateUserSelectedExperType(userSelectedOptioName);
alert(tests);
Code
function validateUserSelectedExperType(inp) {
$.each(splitter.getFirstPaneContent(), function (index, item) {
var splitterinner = splitter.getFirstPaneContent()[index];
var getLabel = splitterinner.getFirstPaneContent()[0];
if (getLabel.getText() == inp) {
return true;
} else {
return false;
}
});
}
You're returning from the nested function, not from the validateUserSelectedExperType function. Set a boolean and update that value instead. At the end, return it:
function validateUserSelectedExperType(inp) {
var flag = false;
$.each(/* ... */, function (index, item) {
// ...
if (getLabel.getText() == inp) {
flag = true;
return false;
}
});
return flag;
}
That's because your return statements are within $.each() anonymous function. Returning falsefrom that function will stop the each loop.
You have to return something for the main function (I can't understand your code logic, so I can't help you in that).