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

General Discussion

Jeff Lange
Jeff Lange
8,788 Points

Using indexOf - how does it know where to look?

In JavaScript strings we just wrote this code:

var part1 = "Hello ";
var part2 = "World!";
var whole = part1 + part2;
console.log(whole + "!!!!");

var length = whole.length;

var index = whole.indexOf("World");

var index2 = whole.indexOf("world");

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

But I'm confused. How does the indexOf in the if statement know to search for the capital W in the variable "index" instead of in "index2"?

1 Answer

It does not. It searches in variable "whole". It call indexOf method for variable whole. whole variable consists of part1 and part2 variable. Hence it searches in "Hello World".

Jeff Lange
Jeff Lange
8,788 Points

Ohhh...right, right, right, because it's not just indexOf it's whole.indexOf.

And since "whole" is made up of "Hello World!" it searches that for the uppercase "W" (which, indeed, it finds). If I changed the value of part 2 to "world" or "adslfjadlf" or whatever, the whole.indexOf wouldn't find a "W" so it would print the "W does not exist" console.log.

That was super helpful! Thank you :)