You-dont-know-js: Comparison with [] value

Created on 30 Sep 2019  路  2Comments  路  Source: getify/You-Dont-Know-JS

Edition: (1st or 2nd)
2nd Edition

Book Title:
Getting Started

Chapter:
Chapter 2: Into JavaScript

Section Title:
Equality

Question:
Which is the justification of the affirmation "If a value in a comparison is [] avoid == and use ==="?
Perhaps I misunderstood the affirmation, but as far as I can understand, 'any object variable' == [] or 'any object variable' === [] equal always to false, because the references don't match. Even if is equal to [].
Am I right?

Most helpful comment

Thank you!
You're right. I had not noticed that:

var a = 0;
var b = "";

a == []; // true
a === []; // false

b == []; // true
b === []; // false

All 2 comments

x == [] means x === [] if x happens to already be an object. but if x is any primitive, then coercion of the [] will occur. Because [] coerces to "", when then coerces to 0, I consider that a coercion gotcha that should just straight up be avoided.

Thank you!
You're right. I had not noticed that:

var a = 0;
var b = "";

a == []; // true
a === []; // false

b == []; // true
b === []; // false

Was this page helpful?
0 / 5 - 0 ratings