skip to Main Content

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"))

enter image description here

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"));

enter image description here

I expected that both code must give me the same results.

2

Answers


  1. 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

    Login or Signup to reply.
  2. It’s because Array#pop() mutates the array so if you iterate over stk and call .pop() on it, you reduce its actual length.

    From MDN:

    The pop() method is a mutating method. It changes the length and the content of this.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search