View Full Version : Slightly Confused by code

sara jane
06-19-2010, 05:46 PM

I've been learning javascript from a fairly decent book and things are going quite well, however, theres an element to the latest task that I'm not understanding very well and was hoping someone on here could help with this:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
<html xmlns=”http://www.w3.org/1999/xhtml”>
<title>Chapter 5: Example 1</title>
<script type=”text/javascript”>
var myString = “Welcome to Wrox books. “;
myString = myString + “The Wrox website is www.wrox.com. “;
myString = myString + “Visit the Wrox website today. Thanks for buying Wrox”;
var foundAtPosition = 0;
var wroxCount = 0;
while (foundAtPosition != -1)
foundAtPosition = myString.indexOf(“Wrox”,foundAtPosition);
if (foundAtPosition != -1)
document.write(“There are “ + wroxCount + “ occurrences of the word Wrox”);

The part I'm not understanding is the foundAtPosition part, the != -1 part seems silly to me it will never be equal to this and therefore the while loop would continually loop over and over.
I know it's not because I've run this code and it performs correctly I just wondered why the loop doesnt continually loop over and why would a value hit -1 at some point.

Many thanks


06-19-2010, 06:08 PM
Hi sara, the foundAtPosition is going to be equal to the first occurrence of the word "Wrox" that it finds.

When you call indexOf(), the first parameter is the string you're searching for, and the second parameter is where to start in the string. indexOf() will either return the element number where it found the string you're searching for, or it will return -1 if it can't find it.

So let's say we have This string:
"My Wrox is Wrox."

The first time through, it will find Wrox at myString[3], then if you move the start point, it will find it at myString[11], then if you repeat that process again, the result will be -1 because it will not be found.

sara jane
06-19-2010, 06:23 PM
Hi Dean440,

Perfect!! I understand now.

Thanks alot