-4

I got an empty array from previously code running,and I wanted to check whether it was empty within an if statement,I used

if (emptyArr) {
  //do something here. 
}

at first,received some weird results,now I know that I should use if (emptyArr.length === 0 ) {} instead,but only for curiosity,what the code block above results in?

2 Answers2

2

An empty array is still an object, and an object reference is always true in an if predicate like that. Thus

if ([]) alert("hello world");

will always trigger the alert.

Pointy
  • 405,095
  • 59
  • 585
  • 614
-1
typeof []
"object"

So as if({}) turns out to be true, if([]) is true too.

Here is question about Why object is true

Community
  • 1
  • 1
Ivan Shmidt
  • 163
  • 1
  • 7