I was intrigued by one the question asked on my So you think you know JavaScript article.
{} + []; // returns 0 ?? 🤔
Enter fullscreen mo...
For further actions, you may consider blocking this person and/or reporting abuse
I felt like I was reading Kyle Simpson's article :D.
Extremely thorough article on JavaScript types. Great job!
Glad to read that Richard. Thank you.
Extremely helpful saved my day.
Glad to read that. 🙂
Now javascript has also the "bigint" primitive type.
Clear and concise, learned something new today, thanks man! Keep it up
Thank you, Christian, for your kind words. I am glad that you learned something out of it. 😀
Great article! Learned a lot.
BTW,
{1} + []
results in an0
. How is this possible?Hi Milindu,
The
{}
is a code block with a value of1
inside. It has nothing to do withAddition operator
outside of it. When parser reads this line it will evaluate1
and move to another expression, which is+ 0
, and will output0
.Why does
{name: 'Aman'} + 0
returns 0?Summary: use TypeScript and explicitly coerce!
TypeScritp = Make Java.
Stay in Java rsrsrsrsrsrsr
why does [].toString() result in an empty string?
great article btw
For {} + [], {} is not an empty object but just an empty block; for [] + {}, {} is an object.
How did we reach these conclusions?
Hi Ravina,
This behavior is how JavaScript engine (e.g V8) starts out by parsing the source code into an Abstract Syntax Tree(AST). For
{}
, JavaScript parser considers it as an empty block because this is the first thing in the statement. But in the case of[] + {}
, the first thing is an array followed by Addition operator.Here's a nice AST explorer to check out. Paste both the statement to verify yourself. 🙂
Thank you!
This was great.