I am trying to break the whole sentence into reverse words, in this case, why do we use let i = splittedText.length-1
instead of let i = splittedText.length
?
Why do we need to subtract 1?
const wordSplit = (text) => {
let splittedText = text.split(" ");
let reversedWords = [];
for(let i = splittedText.length-1; i>=0; i--){
let ele = splittedText[i];
reversedWords.push(ele);
}
const result = reversedWords.join(" ");
return result;
};
const myWord = "I will solve the problem";
console.log( wordSplit(myWord));
2
Answers
Arrays are zero-indexed in javascript. When you have an array with 3 elements, its length will be 3, but the indexes of the elements will be 0, 1, 2. If you you use
i = array.length
, then on the first iteration of your loop you will try to access the element at index 3, which does not exist and will give you an "index out of bounds" error.For illustration lets look at this array of length 3:
Arrays are zero-indexed data structures so, the last element of the array will be length -1. If you use length only, you will get out of bound exception.