johnkors

John Korsnes

JavaScript Arrays: Truth or Dare

| Comments

Okay, I kind of like this one.

JavaScript Arrays #1
1
2
3
4
5
6
7
8
9
10
11
12
13
describe("Empty JavaScript Arrays", function(){
  it("are truthy when standalone", function(){
    [].should.be.ok;
  });
  it("are false compared to a boolean using ==", function(){
    ([] == false).should.be.true;
    ([] == true).should.be.false;
  });
  it("are neither true nor false when compared to a boolean using ===", function(){
    ([] === false).should.be.false;
    ([] === true).should.be.false;
  });
});

Another way of showing the relationship between empty arrays and true/truthy values:

JavaScript Arrays #2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// standalone truthfulness
if([]){
  console.log("Is written to console!");
}

// ==
if([] == false){
  console.log("Also written to console");
}
if([] == true){
  console.log("not this one though");
}

// ===
if([] === false){
  console.log(".. but is NOT written to console..");
}
if([] === true){
  console.log(" and neither is this written to console");
}

Empty arrays boolean evaluation summarized:

  • truthy when by itself (when not compared to a bool)
  • false when compared to a bool using the == operator. JavaScript coerces the empty array to it’s boolean equivalent, which is what happens when we compare using the == operator.
  • NEVER true when compared to either true nor false using the value and type comparison : ===.

Funny side note:

1
[] == ![] // true

The right side ![] converts the array to a boolean true and flips it to false. Then the == operator, since the types are different, converts the left side to a primitive value (by calling [].valueOf()) and ultimately ends up with 0. The right side false also gets converted to a zero, so in the end they compare equal.

Puh.

Comments