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

Form Validation and Manipulation- Checking Values

Can anyone explain why the !=-1 works to validate the email? So what if it's not -1, as stated in the video? How does that validate anything? And how does the computer compute this?

1 Answer

indexOf will return the position of a specified character. In the video, you look for the @ character. If @ is present, indexOf will return a number that represents its position within the email address.

This email address would return 2:

hi@email.com

And this would return 5:

hello@email.com

The number returned is one less than you may expect because the index is zero-based, meaning the first character has an index of 0.

-1 is returned when the character can't be found within the email address. You could argue that false would make more sense for when a character can't be found, but generally in programming, it's best not to mix the type of values returned. -1 doesn't represent a position, it just means the character wasn't found.

If the returned value is anything but -1, it means the @ symbol was found within the email address.

It's only a very basic validation but it means that the user at least typed an email address that contains an @ character.