undefined return in javascript [duplicate] - javascript

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).

Related

When should I use $.getJSON.done() instead of $.getJSON()? [duplicate]

This question already has answers here:
Why does JQuery.getJSON() have a success and a done function?
(2 answers)
Closed 5 years ago.
I would like to know if there are any conceptual differences between these two codes:
Code 1:
$(function(){
var url = "url";
$.getJSON(url, function(data){
console.log(data);
})
});
Code 2:
$(function(){
var url = "url";
$.getJSON(url).done(function(data){
console.log(data);
})
});
In which situation the $.getJson().done() method is most relevant ?
The First one uses a callback function as a second param. This allows you to execute code after the function is completed. Note, you are in a separate function.
The Second also uses a callback function as a promise but it is working different under the hood.
// version one
setTimeout(function() {
doStuff1();
doStuff2();
}, 1000)
// version one - callback
function doStuff1() {
doSomething1("value", function(responce) {
console.log(responce);
});
};
function doSomething1(v, cb) {
if (typeof v === "string") {
cb(true);
} else {
cb(false);
}
return false;
}
// note the function will always return false but the callback gets the value you want
// version 2, class with promise callback
// look at the class function and see how it works slightly differently
function doStuff2() {
var $ = new doSomething2();
$.Something("value").done(function(resp) {
console.log(resp)
});
};
class doSomething2 {
constructor() {
this.v = false;
}
Something(val) {
if (typeof val === "string") {
this.v = true;
} else {
this.v = false;
}
return this;
}
done(cb) {
return cb(this.v);
}
}

Run Function only once in Javascript [duplicate]

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;
};
})();

Why this code doesn't return false? [duplicate]

This question already has answers here:
Short circuit Array.forEach like calling break
(30 answers)
Closed 7 years ago.
function every(array, predictate){
array.forEach(function(x){
if (!predictate(x))
{
return false;
}
});
return true;
}
console.log(every([NaN, NaN, NaN], isNaN));
//true
console.log(every([NaN, NaN, 4], isNaN));
//suppose to return false, but still return true...
The second console.log should return false but it returns true. What did i do wrong?
The return false is the return of the anonymous function used in the forEach. So it does not return anything for every. If you want to use forEach and return false, you have to do like this :
function every(array, predictate) {
var result = true;
array.forEach(function(x) {
if (!predictate(x)) {
result = false;
}
});
return result;
}
Your return false statement is for the forEach callback function, not for the external every.
every will always return true unless you change it to something like:
function every(array, predictate){
var retValue = true;
array.forEach(function(x){
if (!predictate(x))
{
retValue = false;
}
});
return retValue;
}

Run function only once - functional programming JavaScript [duplicate]

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.

How can I exit from a javascript function? [duplicate]

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.

Categories