I'm learning JavaScript and AngularJS.
What's the difference between this code?
function isInArrayNgForeach(field, arr) {
angular.forEach(arr, function(value, key) {
if(field == value)
return true;
});
return false;
} // This returns always false
function isInArrayJavaScript(field, arr) {
for(var i = 0; i < arr.length; i++) {
if(field == arr[i])
return true;
}
return false;
} // This works fine
function isInArray() {
var testArr = ['stack', 'over', 'flow'];
console.log(isInArrayNgForeach('stack', testArr)); // return false
console.log(isInArrayJavaScript('stack', testArr)); // return true
}
My question is: why isInArrayNgForeach always return false? I assume that because there is a function inside of the function, but I'm not sure why.
It's important to note that the forEach method doesn't return anything, and thus, if you try to get the return value of the forEach method, you will get undefined .
The forEach method is also used to loop through arrays, but it uses a function differently than the classic "for loop". The forEach method passes a callback function for each element of an array together with the following parameters: Current Value (required) - The value of the current array element.
forEach() executes the callbackFn function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.
forEach() Function in AngularJS is used to iterate through each item in an array or object. It works similar to the for loop and this loop contains all properties of an object in key-value pairs of an object.
The first option is different because return true;
returns from the function which is passed as parameter to forEach
function not from the outer function isInArrayNgForeach
and that's why the last line return false;
gets called always when the forEach finishes. Which makes the function return false always.
If you change the code like this, tt will return expected result:
function isInArrayNgForeach(field, arr) {
var result = false;
angular.forEach(arr, function(value, key) {
if(field == value)
result = true;
});
return result;
}
function isInArrayNgForeach(field, arr) {
angular.forEach(arr, function(value, key) {
if(field == value)
return true; // You are returning the immediate function here not isInArrayNgForeach
...
To make it work as you intend it to
function isInArrayNgForeach(field, arr) {
var result = false;
angular.forEach(arr, function(value, key) {
if(field == value)
result = true;
});
return result;
} // This returns expected value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With