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

IndexOf

Hi There

I am teaching myself some JS and form validation. But I am having trouble understanding indexOf - I know that if a string exists when using indexOf I get its position (zero based) and if its not there I get a -1 . But why does my code in this jsfiddle specifically this bit

if (theURL.indexOf("http://"))

evaluate to true even when I make the validation intentionally fail - surely this should come back as -1.

Can someone please help me get my head around this.

http://jsfiddle.net/SNXD5/

G

4 Answers

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

Hi Graham,

Try this simple example:

if (-1) { alert("it's true!" };

In the world of JavaScript, -1 is a TRUE value and 0 is a FALSE value, so you can't use indexOf() by itself within a conditional statement; if you do and the string doesn't exist you'll get -1 (TRUE); even worse, if the user types a URL beginning with http://, the indexOf() method will return 0 (FALSE), the exact opposite of what you want!!!! Here's what you want

if (theURL.indexOf("http://") !== 0) {
   document.getElementById('formerror').innerHTML = "URL's must start with http:/"
} // if statement

Ah Graham, I have been trying to catch you on Facebook, I sent a message may have went into the other message folder, was about the donation for the triathlon.

Scott

HI Scott - have accepted the friend request - oh and reactivated the site - but it says it takes up to 24-48 hours although have sent you a FB message too.

G

Dave - please do not take this the wrong - you total !&**!!@ genius.

Therefore if it returns the 0 as in it exists and is at position 0 its false - WOOOOHOOOO!!!!!!!!!!!!!

There is happiness - Dave be thy name!!!!!!!!!