ltbesh ltbesh - 1 month ago 4
Javascript Question

Returning value in underscore each loop does not stop the function

I noticed a strange behaviour, at least one I don't understand, while returning value inside an underscore each loop. My code is the following, it basically test wether or not an element is already present in an array based on its id, like this :

var elements = [{id: "1", name : "foo"},{id : "3", name: "bar"}];

element_exists = function(key, val){
console.log(element[key], val);
if(element[key] == val){
console.log("element exists");
return true;
return false;

console.log("true : ", element_exists("id", "1"));
console.log("false : ", element_exists("id", "2"));

I get the following log in the console :

1 1
element exists
3 1
true : false
1 2
3 2
false : false

My question is why does the function does not return true for the first element ?


@ltbesh You are getting it wrong! The function does return the value & stop. It only continues executing the iterator function for the remaining elements in the input.

You are confusing loop statements with _.each method.

The second parameter to the _.each method is an iterator function. It is basically a function that is executed for every element of the array. So, if you write a return statement in your iterator function, it only terminates that particular function call. The function continues to be called for the remaining elements in the array.