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.
Now javascript has also the "bigint" primitive type.
Great article! Learned a lot.
BTW,
{1} + []results in an0. How is this possible?Hi Milindu,
The
{}is a code block with a value of1inside. It has nothing to do withAddition operatoroutside of it. When parser reads this line it will evaluate1and move to another expression, which is+ 0, and will output0.one issue i believe in the post is the toPrimitive algo for the hint 'Number', in that case no toString will be called only the valueOf will be called.
example : [] + 2;
this will return 2 as [] is directly converted to valueOf not via toString.
one more example in the screenshot.
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. 😀
Extremely helpful saved my day.
Glad to read that. 🙂
Why does
{name: 'Aman'} + 0returns 0?TypeScritp = Make Java.
Stay in Java rsrsrsrsrsrsr
why does [].toString() result in an empty string?
great article btw
This was great.
Thank you!
Summary: use TypeScript and explicitly coerce!
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. 🙂