Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why an empty array equals to an empty string while not to another empty array in javascript? [duplicate]

Tags:

javascript

enter image description here

Can anyone describe the picture above? It is the screenshot of my Chrome dev-tool console.

like image 652
Sejin Jeon Avatar asked May 11 '26 22:05

Sejin Jeon


1 Answers

Because of JavaScript coercion.

[] is loosely equated to "" and thus coerced to string using [].toString() which is equal to "".

And why does [] == [] and [] === [] return false:

the == and === comparison rules if you’re comparing two non-primitive values, like objects (including function and array). Because those values are actually held by reference, both == and === comparisons will simply check whether the references match, not anything about the underlying values.

var a = [1,2,3];
var b = [1,2,3];

var c = "1,2,3";

a == c;     // true
b == c;     // true
a == b;     // false

arrays are by default coerced to strings by simply joining all the values with commas (,) in between.

like image 69
void Avatar answered May 13 '26 12:05

void