Mutations - curly braces positioning

I’m reviving this thread to ask about why the curly braces need to be removed on the for loop in this problem. Does anyone know the reasoning behind this? I’m guessing there is a scoping issue when blocking the for and if statements of my code. Originally, I had curly braces after the for loop and after the “if” condition. Code is below, and any insight would be helpful.

function mutation(arr) {
  var array1 = arr[0].toLowerCase();
  var array2 = arr[1].toLowerCase();   
   
 for (var i=0; i < array2.length; i++) 
   if (array1.indexOf(array2[i]) === -1) 
     return false;
  
    return true;   
}

As I remember it doesn’t has to be removed. Both ways should work. Here is the helpful link about {} curly braces Are braces necessary in one-line statements in JavaScript? - Stack Overflow

In this link Josh K. answered:

This is perfectly valid

if (cond) 
    alert("Condition met!")
else
    alert("Condition not met!")

However it is highly recommended that you always use braces because if you (or someone else) ever expands the statement it will be required.

This same practice follows in all C syntax style languages with bracing. C, C++, Java, even PHP all support one line statement without braces. You have to realize that you are only saving two characters and with some people’s bracing styles you aren’t even saving a line. I prefer a full brace style (like follows) so it tends to be a bit longer. The tradeoff is met very well with the fact you have extremely clear code readability.

if (cond) 
{
    alert("Condition met!")
}
else
{
    alert("Condition not met!")
}
1 Like

Ok, now I’m pretty confused. I recreated my old code before I got rid of the curly braces, and it passes all except the [‘hello’, ‘hey’]. I ran mutation() through the chrome debugger and see that the values 0,1,-1 are console.logged for [‘hello’, ‘hey’], but the function is returning 0 for some reason. However, once the curly braces are removed, it runs perfectly. Old Code:

function mutation(arr) {
  var array1 = arr[0].toLowerCase();
  var array2 = arr[1].toLowerCase();
   
   
 for (var i=0; i < array2.length; i++) {
   if (array1.indexOf(array2[i]) === -1) {
     return false;
   } else {
    return true;
   }
 }  
}

Thanks to you and llima for taking the time to respond. Your solution with curly braces was very helpful, and I see where I went wrong with my ‘old’ code.