I have absolutely no idea why curly braces are not working in this if statement(spoiler alert: solution to mutations question in basic algorithm scripting)

Please can someone help me understand why curly braces were not used in the if statement below:

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

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

I tried including curly braces and making it an if /else statement but it did not work which was one of the reasons I was finding it difficult to solve this question.

function mutation(arr) {

let target = arr[0].toLowerCase();
let test = arr[1].toLowerCase();

 for(let i = 0; i < test.length; i++){
 if(target.indexOf(test[i]) == -1){
  return false
 } else {
  return true  
 }
 }
}

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


I found a similar question that was already asked but it did not seem to answer the question.
Please anyone know the reason why this is happening because I feel if I don’t understand this now it might lead to some unrecognized errors in the future.

For single line bodies for if statements, the curly braces are optional.

if (x < 4)
  console.log("x was less than 4");

is fine, but

if (x < 4)
  console.log("x was less than 4");
  console.log("this is not part of the if statement");

this needs {}s if you want the second line to be part of the if statement.

I am not sure.
Is it probably because of the indexOf method that was used in the conditional statement?

I’m not sure what you’re asking exactly. Is your code not working in some way? Which challenge are you working on?

I have edited your post to include the challenge link and spoiler tags around the working solution.

I am working on the Mutations challenge on the Basic Algorithm Scripting which asked to return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.

here you are testing and giving an answer only for i = 0, that’s why it doesn’t work

2 Likes

Ah yes, I see now. @ilenia is right. Remember that a function immediately stops when it encounters a return statement.

1 Like

Ok now I see.
Did not seem to put that into consideration when I was attempting this
Thanks for the help as I now understand it better

I must have missed that.
Thanks for the help.

ok thank you as I wasn’t entirely sure how to do that

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.