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

What does .indexOf mean?

if can please dumb it down so that i can understand it , thank you!

Example

Search a string for "welcome":

var str = "Hello world, welcome to the universe."; var n = str.indexOf("welcome"); The result of n will be:

13

how is it 13? why?

1 Answer

var str = "Hello world, welcome to the universe."; 
var n = str.indexOf("welcome");

this will find the word 'welcome' and return the index of the first letter ( so it's where the first letter of this word appears )

you have string "Hello world, welcome to the universe."u for instance element on index 3 will be letter 'l', because string indexes begin with 0, so when you call

var n = str.indexOf("welcome");

you will get index of letter 'w', which is 13. Hope that helps.

i get that it finds the word where it appears, but how did it get 13? what is being added up?

take a look string "Hello world, welcome to the universe." the string begins from index 0, so

H - has index 0,

e - 1,

l - 2,

l - 3,

o - 4,

' ' - 5,

w - 6,

o - 7,

r - 8,

l - 9,

d - 10,

, - 11,

' ' - 12,

w - 13,

e - 14,

and so on.

it finds the word 'welcome' and returns the index of the first letter in this word, as you can see from above it's 13.

ohhh it adds everything, i thought just letters. I get it, thank you!