Mutations and the curly bracket

Tell us what’s happening:
Hi! I’m not understanding why [“hello”, "hey] doesn’t work on my code but it does on the exercise’s hint.
The only difference is a curly bracket… see below if you have time, thanks!

Your code so far


// My code
function mutation(arr) {
  let arr2 = arr[0].toLowerCase();
  let arr1 = arr[1].toLowerCase();


  for (let i = 0; i < arr1.length; i++) {
    
    if (arr2.indexOf(arr1[i]) < 0 ) { // this curly bracket
      return false;
    }
    return true;
  }

}

console.log(mutation(["hello", "hey"]));




 // Correct code (FCC's hint)
function mutation(arr) {
  var target = arr[0].toLowerCase()
  var test = arr[1].toLowerCase();
  
  for (var i=0;i<test.length;i++) {
    if (target.indexOf(test[i]) < 0) // no curly bracket
      return false;
  }
  return true;
 }
}
 

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/mutations

So without the curly bracket, the one line (ONLY ONE LINE) following that if statement is executed. Then, the for loop continues.

In your code, on the first iteration, you’re saying either return true, or return false. If you move that return false outside of the for loop, your code would be exactly the same as the provided sample.

1 Like

Hey there–the problem isn’t the curly bracket, although the curly brackets did cause the confusion.

So, in JavaScript this,

if (test == true)
    return "Success!";

and this,

if (test == true) {
    return "Success!";
}

Are the same thing. They do they exact same thing.

In the FCC hint, it says,

for (var i=0;i<test.length;i++) {
  if (target.indexOf(test[i]) < 0) // no curly bracket
    return false;
}
return true;

Notice that the if statement is inside the for loop, and returning true is outside the for loop. I personally never write if statements without brackets to avoid this kind of confusion, but at the end of the day it is just a style thing.

1 Like

Good to know! also thanks for the nice and quick reply :slight_smile:

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

Thank you for understanding.

2 Likes