normyp
normyp

Reputation: 184

Undefined array.length returns true not false

I'm currently working through the MDN JavaScript documentation and in one of the beginner exercises it claims that: (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Evaluating_variables)

The undefined value behaves as false when used in a boolean context.

var myArray = [];
if (!myArray[0]) myFunction();

However, my brain being simple can't work with opposites in an if statement. Therefore I re-wrote it using the .length function:

var myArray = [];
if(myArray.length === 1) {
  console.log("How?");
} else {
  console.log("Hello World!");
}

What I was expecting was Hello World! to be printed because the Array is undefined and should return false however it is returning 1.

Any explanation as to why this is happening would be great!

Upvotes: 2

Views: 1403

Answers (3)

Yarl
Yarl

Reputation: 798

If you’re in doubts debugging check with console output or inspect the variables/create you watch.

var myArray = [];
console.log(!myArray);
console.log(!myArray[0]);

printIt(myArray.length === 0)
printIt(myArray.length === 1)

function printIt(ok) { 
  if(ok) { console.log("Ok."); }
  else { console.log("Not ok."); } 
}

If you’re about to check if array is empty you should express you desire by code, so:

if(array.length === 0) …

If you’re about to check if variable is declared …

var array;
console.log(!array);

array = [];
console.log(!array);

console.log(Array.isArray(array));

let u = "u";
console.log(Array.isArray(u));

If you need to aware of both …

var array;
//console.log(array.length);

array = [];

if(array && Array.isArray(array) && array.length === 0) { array.push("Hi!"); console.log(array[0]);}

let w = "w";
if(w && Array.isArray(w)) { console.log(w);}

Upvotes: 0

PhDiZone
PhDiZone

Reputation: 1

var myArray = [];
if (!myArray[0]) myFunction();

myArray[0] - In this array initialization default zero will take 1.

if(myArray.length === 1) - In this line, it will return to get the opposite result of the initialization. So, it printed to be 1.

Upvotes: 0

crownlessking
crownlessking

Reputation: 1232

For the test myArray.length === 1 to evaluate to true the array must contain exactly one element. But you didn't put anything in there so the test failed and Hello World! was printed.

Think of an array as a container.

var myArray; // is undefined

var myArray = [] // is NOT undefined

var myArray = [] is empty but it is a valid array.

Therefore, using .length, a better test would have been:

if (myArray.length === 0)

Then How? would have been printed.

Because there is nothing in your array, the length is 0.

Upvotes: 1

Related Questions