Home > Software engineering >  Getting undefined with strict equality operator but not with normal equality operator
Getting undefined with strict equality operator but not with normal equality operator

Time:10-17

function sym(...args) {
  let arr = [...args];

  while(!arr.length === 0) {
      arr.pop();
      console.log(arr.length);
  }
}

console.log(sym([1,2,5],[2,3,5],[3,4,5]));

I was trying to figure one problem out but another problem came up. Can someone please explain to me why this logs undefined? The strict equality operator logs undefined but the normal equality operator doesn't, even though arr.length returns a number.

CodePudding user response:

! has higher operator precedence than ===.

while(!arr.length === 0) {

is equivalent to

while((!arr.length) === 0) {

Comparing a boolean to a number will never work with ===, but it will sometimes work with == - but either way, that isn't what you want. Use !== 0 instead.

function sym(...args) {
  let arr = [...args];

  while(arr.length !== 0) {
      arr.pop();
  }
  return arr;
}

console.log(sym([1,2,5],[2,3,5],[3,4,5]));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related