The code below runs fine. No Problem
const isPalindrome = word => {
const stk = [];
let rword = "";
for(let i = 0; i < word.length; i++){
stk.push(word[i]);
}
console.log(stk)
console.log(stk.length)
for(let i = 0; i < word.length; i++){
rword += stk.pop();
console.log(rword)
}
return word === rword;
}
console.log(isPalindrome("racecar"))
But When I run this code with stk.length, it runs only 4 times in the loop. Why such behaviour?
const isPalindrome = (word) => {
const stk = [];
let rword = "";
for (let i = 0; i < word.length; i++) {
stk.push(word[i]);
}
console.log(stk);
console.log(stk.length);
for (let i = 0; i < stk.length; i++) {
rword += stk.pop();
console.log(rword);
}
return word === rword;
};
console.log(isPalindrome("racecar"));
I expected that both code must give me the same results.
2
Answers
Cause when u loop stk array, u pop an element from stk => stk’s length decrease.
So after looped 4 times the stk’s length becomes 4 and i increasing to 4 too, and the condition i<stk.length no longer match
so the loop break after 4 times
That’s why the 1st example using word’s length instead of stk
It’s because
Array#pop()
mutates the array so if you iterate overstk
and call.pop()
on it, you reduce its actual length.From MDN: