Question about index of "=-1" and "<0"

Why can’t I use “target.indexOf(test[i] = -1)” instead of "<0"as index of -1 means test element doesn’t exist in target element? Anybody can help me with this?

Question goes like this:

Mutations

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.

For example, ["hello", "Hello"] , should return true because all of the letters in the second string are present in the first, ignoring case.

The arguments ["hello", "hey"] should return false because the string hello does not contain a y .

Lastly, ["Alien", "line"] , should return true because all of the letters in line are present in Alien .

  **Your code so far**

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

mutation(["hello", "hey"]);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36

Challenge: Mutations

Link to the challenge:

That’s an assignment, not a comparison. Plus it’s WITHIN the function-call.
And as a assignment doesn’t have a return-value, that thing is “target.indexOf(None)”.

1 Like

The indexOf method in the array returns -1 if the element is not present in the array.

So you can also frame your condition as

if (target.indexOf(test[i]) === -1)

…then return false.

It means that if indexOf() method returns -1 for the presence of test[i] in target then return false.
So it is basically a condition check here, not an assignment.

2 Likes

Wow, it works after I change it from “= -1” to “==-1” or “=== -1”, thanks!

it works after I change it from “= -1” to “==-1” or “=== -1”, thanks!

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