[ Solved ] Why, the following code's output is 7? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

[ Solved ] Why, the following code's output is 7?

let str = "Locate Me"; let outPut = str.indexOf("M", 4); console.log(outPut);

13th Sep 2020, 12:31 PM
Noob Programmer
Noob Programmer - avatar
9 Answers
13th Sep 2020, 12:50 PM
Noob Programmer
Noob Programmer - avatar
13th Sep 2020, 12:35 PM
Noob Programmer
Noob Programmer - avatar
+ 3
13th Sep 2020, 12:49 PM
Vadivelan
+ 3
IndexOf() is used to return the index(position or location) of the first occurance a specified character or string and the indexing starts from 0, including spaces. So in 'Locate Me', M's index is 7.
14th Sep 2020, 5:34 PM
Aheebwa Michael
Aheebwa Michael - avatar
+ 3
Because the first occurance of "M" starting with the fifth character (t) is the 7th index (8th character) 🤖
15th Sep 2020, 3:25 AM
Sanjay Kamath
Sanjay Kamath - avatar
+ 2
♤♢☞ 𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 ☜♢♤ then, shouldn't the output has to be 3 or 4?
13th Sep 2020, 12:41 PM
Noob Programmer
Noob Programmer - avatar
+ 2
♤♢☞ 𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 ☜♢♤ so you are telling that, it starts searching from specified value but count positions from zero?
13th Sep 2020, 12:48 PM
Noob Programmer
Noob Programmer - avatar
+ 2
Abir Sheikh the second parameter only specifies the index position of where you should start the search for the position of the first occurence of the value. It does not change the index positions. Here is an example: let str = "money made"; let output = str. indexOf("m") ; console.log(output); // 0 let output2 = str. indexOf("m", 4) ; console.log(output2);// 6 Hope this helps.
14th Sep 2020, 6:14 PM
Devotha Mwenda
Devotha Mwenda - avatar
+ 2
It is because the indexOf() method returns the position of the first occurrence of a specified value in a string. String.indexOf(searchvalue, start) Your second parameter tells you at which position to start the search. It's default value is 0. I hope you understood 🙂 😎 👇 L o c a t e m e 0 1 2 3 4 5 6 7 8 Hope it helped ! Happy Coding </>
14th Sep 2020, 11:19 PM
Raj Srivastava
Raj Srivastava - avatar