Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Foundations Strings Methods: Part 1

What is the significance of !==-1 here?

if(whole.indexOf("W") !==-1) {
console.log("W exists in string")
} else {
console.log("W does not exist");
}

I am a little confused about what !==-1 means in this statement. I know it literally means does not equal -1, but how does this little piece relate to the big picture (this if/ else function)? I can put anything in there it seems and it returns as W exists, but when I do not include anything after ("W"), I receive the else statement. Can anybody describe what is happening here? Thank you!!

1 Answer

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

You use the indexOf() method to see if one or more letters exists in a string. So whole.indexOf("W") searches the string contained in the variable whole for the letter "W". If indexOf() finds a match it returns a number indicating where in the searched string the match occurs, with 0 being the first letter of the string and 1 being the second letter of the string, and so on.

If no match is found indexOf() returns -1. So the if/else statement you wrote basically looks for 'W' in the string. If it is there indexOf() will return a value of 0 or more. If it's not there, indexOf() returns -1 or no match.

Thank you that helps me a bit!