Home > Enterprise >  Stuck on .indexOf property. Confused on how they got this answer? Code included. (Javascript)
Stuck on .indexOf property. Confused on how they got this answer? Code included. (Javascript)

Time:01-01

Here is the code below. So I understand lastChar would be last character in the string, and indexOf returns a character that you are searching for. I'm getting confused on how they got 18 for the second answer. Any help would be great! Thank you.

 var sentence = 'welcome to bootcamp prep';
 var lastChar = sentence[sentence.length - 1];
 console.log(lastChar); //  -answer= p 
 console.log(sentence.indexOf(lastChar)); // ? -answer=18..??? 

CodePudding user response:

The indexOf function of a string does not return a character but rather returns the position of the first place that string or character is found, not the character itself.

In this question, the last character is "p", as found by this line:

var lastChar = sentence[sentence.length - 1];

However when looking at the string, you can see that the letter "p" is found more than once:

"welcome to bootcamp prep"
//                 ^ ^  ^
//                18 20 23

The numbers indicated in the comment (18, 20, and 23) represent the indexes (locations) of the character within the string.

What do these indexes mean? In JavaScript, indexes start at 0, so the first letter ("w") will be at index 0. In this string, the character "p" is found at places 19, 21, and 24, which translate to the indexes 18, 20, and 23.

The first instance of the searched string "p" is at index 18. Therefore, when running this line:

console.log(sentence.indexOf(lastChar)); // 18

The result will be 18, the index of the first instance of the last character.

(Side note: assuming you are a beginner when it comes to JavaScript - try not to use the var keyword whenever possible. If the variable needs to change, use let, or if the variable stays the same, use const.)

CodePudding user response:

Because indexOf returns the first letter that is found matching the argument.

welcome to bootcam[p] <-- here prep is found.

JavaScript uses primitive data types so you string is just a string and holds no reference to the original value.

CodePudding user response:

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

The indexOf() doesn't return the character, it return the position of the character which will be 18.

  • Related