+ 2

how is slice() working here?

var str = 'i love sololearn!'; var x = -5; document.write(str.slice(--x)); //output:learn

5th Sep 2018, 10:52 AM
pro
pro - avatar
2 Answers
+ 11
The slice() method extracts a part of the string. So, we have the string "I love sololearn!" x = -5. => --x = -1-5 = -6 When we give a negative integer as argument in the slice() method, it starts extracting from the end. Hence it extracts 6 characters from " ! " to " l ". Therefore, the program outputs - learn! NOTE - The output is " learn! " and not " learn " (note the ! ). You did some mistake in writing the question. â˜ș Hope it helps!
5th Sep 2018, 11:07 AM
Nikhil
Nikhil - avatar
0
Note that x=-6, so... i love solo l e a r n ! 6 5 4 3 2 1 Look tha from "!" to "l" is exactaly 6 caracteres.
5th Sep 2018, 11:03 PM
Mr Genesis
Mr Genesis - avatar