learningjavascriptks learningjavascriptks - 3 months ago 9
Javascript Question

For loop with and without curly braces in filter method works differently?

I have this for loop in my code which works properly without curly braces(took me hours to figure out), in the function forTheScope, which doesn't work with curly braces.I want to know why?

function destroyer(arr) {
// Remove all the values
a=[];
for(var b=0; b<arguments.length; b++ ) {
a.push(arguments[b]);
}

function forTheScope(item) {
debugger;
for (var m = 1; m < a.length; m++) // this for loop works
if (item == a[m]) // but when i put curly braces, it doesn't?
return false; //
return true; //
}

/*===== This is the for loop with braces =====
function forTheScope(item) {
debugger;
for (var m = 1; m < a.length; m++) {
if (item == a[m]) {
return false;
} else {
return true;
}
}
}
========== End of the loop ==========*/

return a[0].filter(function filterArray(item,index,array) {
return forTheScope(item);
});
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Answer

This code:

for (var m = 1; m < a.length; m++)
  if (item == a[m])
    return false;
return true;

is interpreted as exactly as if it were written like this:

for (var m = 1; m < a.length; m++) {
  if (item == a[m])
    return false;
}
return true;

A for loop header is syntactically followed by a single statement. That if statement, in turn, fills that requirement. However, wrapping the whole thing in { } also creates a single "compound" statement.

Of course, if the { } were added some other way, then things would be different.

edit — OK, now that you've updated the question to include the errant version, it's clear what the difference is. Your code is different in a particular and very significant way from the working version, and it really has nothing to do with { }. It's that else that's the problem:

for (var m = 1; m < a.length; m++) {
  if (item == a[m]) {
   return false;  
  } else {
   return true;
  }
}

You've moved the return true into the else clause, so now it's inside the loop instead of outside. In the working version, or in my version with { } above, it's outside the loop and so won't happen until the loop is completely finished (unless the loop exits with return false; first).

In your version, the very first iteration of the loop will either exit the function with return false; or else it will exit with return true;. The loop will never get any further than that first iteration.

Comments