DEV Community

Cover image for Yes, {} + [] = 0. No, JavaScript Isn’t Broken

Yes, {} + [] = 0. No, JavaScript Isn’t Broken

Sylwia Laskowska on October 29, 2026

JavaScript is a legendary programming language. Created in the mid-1990s in just 10 days, it was born during the browser wars, when Netscape was tr...
Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Ok, see you folks! 😆
airplane

Collapse
 
georgekobaidze profile image
Giorgi Kobaidze •

My aviation nerd eyes instantly spotted the Lufthansa logo 😄

Nice article by the way!🔥

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Thank you so much! Hahaha, Giorgi, you're right, the logo is actually there! You've got a good eye! Although I have to say, I feel like Lufthansa has gone a bit downhill lately, and these days I actually prefer Polish LOT! 😄

Thread Thread
 
georgekobaidze profile image
Giorgi Kobaidze •

Yeah, I've noticed that too. It's closer to a budget airline than a luxury one.
I haven't flown with LOT Polish Airlines though.

Thread Thread
 
sylwia-lask profile image
Sylwia Laskowska •

Hahaha, on LOT you even get a sweet bun! And seriously, it's actually pretty good! I think they bake them fresh regularly. You can also get beer or wine in a plastic cup. 😅 Although on some flights they seem to keep that a secret, and you have to know to ask for it! 😂 I usually go for the wine, but there's always that fear that one unexpected bout of turbulence will leave me completely covered in it. XDDD

Thread Thread
 
georgekobaidze profile image
Giorgi Kobaidze •

You folks are on fire! A great country with an airline THAT good... Poland is really out there going for being the best country in Europe. And it's working. 😄

Collapse
 
francistrdev profile image
FrancisTRᴅᴇᴠ •

This is the most JavaScript thing I've seen, and I am not disappointed XD

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Hahaha, Francis, this is just the tip of the iceberg when it comes to JavaScript weirdness!

Collapse
 
mikky_986f0099d2222a profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
Mikky •

Hello.
How are you?
Can we collaborate with us?
Please let me know if you’d be open to chatting.
I look forward to hearing from you.
Best regards

Collapse
 
xulingfeng profile image
xulingfeng •

That’s weird. I never get notifications for your posts. I only found this fantastic article more than ten hours late. Must be a bug on Dev.to!😂😍

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Hahaha, who knows, maybe it's all part of some conspiracy! 😂

Collapse
 
kenwalger profile image
Ken W Alger •

JavaScript is one of those languages where you can explain exactly why something happens, walk through every step of the specification, demonstrate that the implementation is behaving correctly, and still conclude that the language has made some questionable life choices.

The distinction between {} + [] and ({} + []) is particularly entertaining. Same characters, different parsing context, entirely different result.

Glad to see the series back! If this is what two hours at Frankfurt Airport produces, perhaps longer layovers should be encouraged.

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Hahaha, exactly! Everything makes sense, everything has a perfectly logical explanation, and yet it never stops being funny, even after all these years!

And as for airports, I actually quite enjoy writing there! It's only when I'm at an airport that I realize just how much time writing articles really takes. Somehow, when I'm at home, I don't notice it nearly as much. 😂

Collapse
 
pengeszikra profile image
Peter Vivo •

Hi Sylwia! JS is my favorite programming language, as you know, since Adobe killed Flash. But honestly, JS is better because it’s free to use. Maybe you could try TDM = Travel Development Method, which is also a vibe coding aberration. It means nothing more than programming while travelling. By the way, I’m happy to have found a similar concept in UMGD.

But let’s get back to JS. I’m a really big fan of it, which is why I argue for JSDoc instead of TS. These positive feelings also led me to create mordorjs, which, at the end of the day, is pure JS. It just uses a strange ability of JS that lets you write working code in a one-character-wide format.

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Hahaha, Peter, yes, I know how much you love JavaScript! I personally use TypeScript, but I totally get your point!

Actually, just the day before yesterday, I was chatting with some fellow developers in Munich, and we started reminiscing about the old days when TypeScript was just emerging. I remember we were a bit hesitant to adopt it because, well, what if Microsoft decided to abandon the project?

But what eventually convinced us was that TypeScript compiled down to pretty clean, readable JavaScript. That was our main argument: we could always go back to that slightly crazy but beautiful language!

Collapse
 
pengeszikra profile image
Peter Vivo •

Right now thanks to open script behiaviour of TypeScript any one can fork it, and make it own verison with own solution, so right now TS is bit versatile compared to JS, there is need to wait a new upgradding in every years.

Collapse
 
gramli profile image
Daniel Balcarek •

Only JavaScript developers can spend 10 minutes explaining why {} + [] equals 0 and then proudly say, “See? It makes perfect sense!” 😂

I think that’s called Stockholm syndrome. 🤣

Just kidding! Great article, even this backend developer enjoyed reading it! 🤣

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Hahaha, thank you! 😂 And yes, that's exactly how it works! I think they should use this article in psychology classes to illustrate Stockholm syndrome, so students can truly understand just how serious this condition is! 😂😂😂

Collapse
 
nyaomaru profile image
nyaomaru •

JavaScript has so many deep parts or maybe shallow parts? 😹

I always find it funny how something as simple as an empty object and an empty array can behave so differently depending on how the parser sees them.

These little quirks are one of the reasons JavaScript keeps surprising us. 🐟

As always, your article was really easy and fun to read!

Have a safe trip home! ✈️😸

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Aww, thank you! ❤️ I'm already back home! :) And exactly! This kind of knowledge probably won't be very useful in our everyday coding. Although I remember there was (and I think there still is) a website called Return True to Win, where knowing these weird JavaScript tricks actually came in handy!

I remember joking with my colleagues at work that one day we'd give someone those challenges during a job interview. And then, a few years later, someone actually gave me one of those challenges in an interview! 😂

Collapse
 
nyaomaru profile image
nyaomaru •

Haha, that’s amazing 😹
The fact that a joke challenge came back as a real interview question years later is peak JavaScript. 😹

And glad you made it home safely! 😸

Thread Thread
 
sylwia-lask profile image
Sylwia Laskowska •

Thank you! By the way, funny story: I actually didn't get that job! And those were very different times. The job market wasn't nearly as competitive as it is today, and if you were a good developer, finding a job was relatively easy.

I actually did pretty well in that interview, but they rejected me because they thought I wasn't... senior enough, and that junior developers wouldn't respect me. XDDD

Which is especially hilarious now, when junior developers sometimes call me five times a day with every possible question imaginable! 😂

Thread Thread
 
nyaomaru profile image
nyaomaru •

I’m honestly surprised you didn’t get the job! 😹

If I were the one hiring, I think I would’ve hired you.

And knowing that juniors now call you five times a day makes the story even funnier. 😹

Thread Thread
 
sylwia-lask profile image
Sylwia Laskowska •

Hahaha, thank you! 😄 But honestly, it all worked out for the best in the end!

Collapse
 
varshithvhegde profile image
Varshith V Hegde • • Edited

Javascript is such a fun language it makes me frustrated everytime 😂

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

You're not the only one! 😂

Collapse
 
varshithvhegde profile image
Varshith V Hegde •

It's kind of love hate relationship 😂😂

Thread Thread
 
sylwia-lask profile image
Sylwia Laskowska •

Hahahaha exactly 😂😂😂

Collapse
 
shubhradev profile image
Shubhra Pokhariya •

Imagine explaining this in a code review: "No, the empty block isn't useless. It's what gets us zero 😂" Also love that adding just one pair of parentheses makes JavaScript treat {} as an object. Can't wait for the {} + {} one, Sylwia!

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Hahaha, I doubt it would even make it to code review! More likely, someone would be sitting there wondering, "Why the hell isn't this code working?!" 😂

Collapse
 
futuritous profile image
Futuritous •

What if the big boys decide they'll use Rust for web from now on and slowly deprecate Javascript? 😂

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Hahaha, we actually already had someone suggesting exactly that in this discussion, @unitbuilds! 😂 But my first question would be: what about DOM access?

Collapse
 
futuritous profile image
Futuritous •

Well, for DOM they'll just have to write an extended Rust API. like node / bun did with server side Javascript. At least we'll no longer have this legacy language hiccups 😂

Collapse
 
unitbuilds profile image
UnitBuilds •

The better question is why? DOM attacks are quite common and because they're pattern driven, 1 attack vector works on numerous sites. Having the DOM available also makes it easier for sites to get cloned, whereas with WASM, everything becomes more difficult, yet for developers, actually easier, because they can write once, deploy everywhere and debug however they like before publishing and if errors occur, that's why we use log-sinks? The DOM existed when it had to be human legible, that's not the case anymore, that's become a security risk

Collapse
 
mikky_986f0099d2222a profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
Mikky •

Hello
How are you?
Would it be possible to collaborate with us?
Please let me know if you’d be open to chatting.
I look forward to hearing from you.
Best regards

Collapse
 
stackmasteraliza profile image
Aliza Ali •

The best part is that the answer depends on where you type it. As a statement, {} is an empty block, so you're really evaluating +[], which is 0. But put it in expression position, like console.log({} + []) or const x = {} + [], and you get "[object Object]" because now both sides go through ToPrimitive and string concatenation. Bonus chaos for the {} + {} sequel: modern Chrome DevTools wraps input that starts with { in parentheses, so the console may not even show you the statement version. Safe flight!

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Exactly! That's why I mentioned that the result can vary depending on the context! 😄 Although when I type {} + [] into Chrome DevTools without parentheses, I still get 0!

Collapse
 
stackmasteraliza profile image
Aliza Ali •

You're right, I overstated that! Chrome only wraps the input in parentheses when it starts with { AND ends with }, so {} + [] still runs as a statement and gives 0. {} + {} is the one that gets wrapped, which is why DevTools shows "[object Object][object Object]" there instead of NaN. Perfect setup for your next post!

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️ •

Lots of people misunderstand {} + [] = 0 to be the actual problem, because it looks unintuitive and illogical.
But the point isn't actually that {} + [] doesn't follow defined rules; of course it does, and under those rules it makes perfect sense, the same way that 255 + 1 = 0 makes sense if we define + to operate on bytes with naive overflow semantics.

The deeper point is that {} + [] is an edge-case that showcases a deeper problem with JS, and that isn't inconsistency, but complexity. Type coercion rules try too hard to make operations work between types where those operations make no sense in the first place. You can't "add" an object to an array, and the language shouldn't try to produce any result no matter how meaningless, it should simply refuse the nonsensical operation entirely.

{} + [] should simply be NaN and raise an error in strict mode, because the operation has no meaningful result and if it happens in your code, you probably have a bug somewhere and would benefit from being told about it.

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

I think we all know that, but here's the catch: we can't break the old web. Backward compatibility is practically sacred in JavaScript.

I mean, that's literally why we have Array.prototype.includes() instead of the arguably much nicer Array.prototype.contains(): because of old MooTools compatibility issues! 😂

Sometimes JavaScript isn't about what makes the most sense, but about keeping websites from 15 years ago running.

Collapse
 
sinarezaei profile image
Sina Rezaei •

One thing worth remembering is that JavaScript's object semantics can become a production security issue, not just a source of funny console output.

There's a good example in qs (CVE-2026-82417). An attacker could influence an object's shape through query parameters, and later qs.stringify() would try to invoke constructor.isBuffer without checking whether it was actually callable. That could trigger a TypeError and cause a DoS.

It's a different edge of JavaScript than {} + [], but the underlying lesson is similar: what looks like a perfectly ordinary object isn't necessarily what the next operation expects.

That's why I think understanding these language rules matters beyond passing a JavaScript interview.

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Oh, I didn't know about this one! But that's exactly the thing with JavaScript. It's not always just about funny console tricks. Sometimes making assumptions about objects can have some really serious consequences!

Collapse
 
sinarezaei profile image
Sina Rezaei •

There's another interesting edge case with coercion: Symbol.toPrimitive. It's not just about how an object gets converted to a string or number. An object can actually control what happens during that conversion.

I've seen this become particularly relevant with custom value objects in financial systems. Imagine a Money object used in a calculation, but its primitive conversion returns a formatted string for display. Suddenly, an expression like total + amount can switch from numeric addition to string concatenation, depending on which object is involved.

That's one reason I prefer explicit methods like money.add(other) and money.toMinorUnits() over relying on implicit conversion. The language is doing exactly what the spec says, but the business logic might be doing something completely different from what the developer intended.

Thread Thread
 
sylwia-lask profile image
Sylwia Laskowska •

Exactly! Symbol.toPrimitive is a really useful feature, especially when you want explicit control over how objects are converted to primitive values. But interestingly, it was only introduced in ES6, back in 2015. Meanwhile, weird behaviors like {} + [] have their roots in the earliest days of JavaScript, when the language was famously put together in a rush. And decades later, we're still living with some of those decisions! 😂

Thread Thread
 
sinarezaei profile image
Sina Rezaei •

That's an interesting distinction. The coercion mechanism itself is much older, but Symbol.toPrimitive made the conversion hook explicit and gave objects more control over it.

One less obvious place where this matters is property-key conversion. Consider an object used as a dynamic key:

const key = {
  [Symbol.toPrimitive]() {
    return "__proto__";
  }
};

const config = {};
config[key] = { isAdmin: true };
Enter fullscreen mode Exit fullscreen mode

The assignment implicitly converts key into a property key. It doesn't remain an object reference. In this case, it resolves to "__proto__", which interacts with the inherited prototype setter rather than behaving like an ordinary data key.

This alone isn't a complete prototype pollution vulnerability, but in a system that dynamically builds configuration objects from values crossing plugin or extension boundaries, these conversion rules become part of the security surface.

That's why I think coercion deserves more attention than it usually gets. The interesting part isn't just what value an expression returns, but what operations JavaScript executes to get there.

Collapse
 
dhiraj-shrotri profile image
Dhiraj Shrotri •

I dislike people who make fun of JS as a coding language by point out its weird parts. JavaScript was originally designed to be a lightweight scripting language that allowed non-programmers to add interactivity to web pages. Over time, it evolved far beyond that original purpose and now powers everything from frontend applications and backend services to mobile apps and desktop software.

I think it's unfair to judge a language solely by its weirdest edge cases, especially when you consider how much its scope has expanded over the years. If you take almost any language and stretch it to support such a wide variety of use cases, you're bound to accumulate some quirks along the way. Just look at Python!

On a related note, I absolutely love this podcast episode about the origins of JavaScript. It's a fascinating listen and provides some great historical context for why the language is the way it is.

The Origins of JavaScript

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

But that's exactly what I wrote about in the article! How JavaScript came to be, how much it has evolved over the years, and why it still has to preserve all those quirks for the sake of backward compatibility.

And besides, think about how much I must love this language if I'm willing to dig into its weirdest corners and explain exactly why they work the way they do!

Making fun of JavaScript's quirks doesn't mean I don't appreciate it. Quite the opposite! ❤️

Collapse
 
dhiraj-shrotri profile image
Dhiraj Shrotri •

I'm really sorry, I should've phrased my comment better. I meant to agree with everything you said in the article and wasn't really accusing you of making fun of JS.

Thread Thread
 
sylwia-lask profile image
Sylwia Laskowska •

Hahaha, no worries at all! 😄 I just wanted to clarify what I meant. I'll always defend JavaScript! :D ❤️

Collapse
 
newadventuresinit profile image
Dirk Mattig •

With a bit of good will you could say that JavaScript simply points out that the union of the empty set with itself is the empty set.
Very elegant 🤪

🎃 Happy Halloween ! 🎃

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Hahaha, beautiful! 😂 I should've waited just one more day and marketed this article as a Halloween horror story! 🎃

Collapse
 
unitbuilds profile image
UnitBuilds •

Honestly, Javascript is overrated. What people actually cling to, is node.js. Which also, is overrated. I've been knee deep into WASM and how different languages can compile down to opcodes, which can be interpreted by wasm and run on any device, even python... But JS, generally requires V8, which means that in order to compile to wasm, you need to run a full-fat V8 compiler... In a WASM... That's just stupid design imo. You intentionally rely on bloat, which isnt even relevant and does nothing but expand the work required for the outcome? take MCP tooling (I actually have alot of gripes with it...), you implement a tool, it uses JSON. So for each tool call, it needs to be serialized and deserialized? Oh but it gets worse, you need to run a full Node.js server, just to execute it? As opposed to a 10mb binary in Rust and no serialization with binary representation for the tool... You can get the exact same outcome, but at less than 100th the cost, not even by losing anything, just stripping bloat. It's like using a site with 100 ads loaded, vs a simple google search. JS is 1 of the most convoluted pieces of software in existence, it cant compile down to opcodes, it cant execute without everything loaded, it cant be made standalone, without all the bloat, it's simply inefficient and yet people use it, because 'it's easy' even though, now that we're in the days where AI does all the coding, it literally makes no sense using JS anymore?

Rant aside, anyone here willing to cut JS altogether? Or are you too vested in it, to just replace it?

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

But that's not quite how it works! 😅 First of all, JavaScript absolutely does compile to machine code thanks to JIT compilation. Modern JavaScript engines are fast enough that, for applications that don't require computationally intensive work in the browser (which is the vast majority of applications we build every day), JavaScript is perfectly sufficient.

And WebAssembly isn't a drop-in replacement for JavaScript. WASM doesn't have direct access to the DOM, so we still have to account for the overhead of crossing the JS/WASM boundary.

I'm also genuinely confused by your claim that you need to run V8 inside WASM. Why would you? I've written quite a lot of WebAssembly code in Rust, and I've never had to run V8 inside it. Where is that requirement coming from?

As for MCP, it's a language-agnostic protocol. Yes, standard MCP messages use JSON-RPC, but that's a property of the protocol, not of JavaScript. You can implement an MCP server in Rust without Node.js.

Don't get me wrong, I'm a big fan of WebAssembly, and I absolutely see its advantages for computationally intensive tasks. But I'm genuinely curious: where exactly do you see WASM providing such a massive advantage over JavaScript in typical everyday web applications?

Collapse
 
unitbuilds profile image
UnitBuilds •

Sorry, I should probably clarify. JS does not compile down to standalone opcodes. It needs the JIT compiler in order to function, so you're forced to bundle it with QuickJS, or V8 if you want full functionality. That kind of beats the whole point of WASM, which is meant to be self-contained binaries that execute anywhere.

Regarding MCP servers, yes, you can write a server in rust and the tools, but the default is JSON-RPC, which imo is wasted ops, given that it's serialization and deserialization, when it's a remote server, sure, a few ms makes little difference, but if we actually do the summation of that, in the past few years, how many compute-years have been wasted to serialization and deserialization of tools? Not to mention how many PB of memory has been locked globally, to host the node.js tool servers given that's the standard approach with Electron based IDEs.

The biggest issue, is that JS earned it's keep, by being 'simple to write', which isnt all that relevant anymore, given AI does most of the writing. The problem is, for now, the internet is still obsessed with JS, but if we dropped the baggage, started clean, WASM would win over HTML + JS, because instead of JIT compilation, we'd have static binaries we could execute and we'd be able to make full use of GPUs. You could run CoD in browser and you wouldnt know the difference vs a desktop app, except, you'd have the added advantage that it's sandboxed, so you're actually safer than running it natively.

Most of the internet's website vulnerability stem from JS, these exploits put people at risk, where WASM isolates that risk to a runtime. We could have a safer, more efficient, more performant internet, if we unilaterally dropped JS. And while it's unfeasible today, it's inevitable in the future.

My argument for dropping JS, is the same as my argument for dropping Linux, because they stem from the same origin. If all of the web ran on WASM, we wouldnt need JS, HTML, or Linux for that matter. We could save double digital percentile of global compute, without losing any capability, infact most things would run better. That's not something we can ignore with the current state of the world. Each linux host running in cloud is an ubuntu or alpine instance, that's 300mb of ram, 1Ghz of compute, 1-10gb of storage. Add node.js, 150mb ram, 0.5Ghz, 150mb of storage, add V8, that's another 300mb of ram, 1Ghz, 150mb of storage. Those sound like tiny figures, till you sum them up. We're running inefficiently, to the point that we're killing the planet in the process, we could have all we have today, but at a fraction of the compute cost, with better security, better performance, better compatibility, all at the price of slightly longer compile times? Seems a worthwhile tradeoff to me?

WASM as a platform, isnt 'ripe' today, it's designing for the future, to push adoption and awareness, to get the world on-boarded, so we can finally start getting rid of the legacy baggage, the same way we did with Flash.

Thread Thread
 
sylwia-lask profile image
Sylwia Laskowska •

That's quite a vision! 😄 But I'm genuinely curious: how would you actually go about starting this revolution in today's world, when practically the entire web is built around HTML and JavaScript, and so much of our infrastructure relies on Linux?

We're talking about decades of development, countless applications, frameworks, libraries, tools, and entire ecosystems built around these technologies. Even if WASM could eventually replace some of them, how would you convince companies and developers to abandon everything they've invested in and essentially start over?

What would be the first realistic step towards making this happen? Because I can see the theoretical appeal, but I'm struggling to imagine how we'd actually get from where we are today to the future you're describing.

Thread Thread
 
unitbuilds profile image
UnitBuilds •

Tbh, it's inevitable, probably in the next 5 years we'll see a shift where the majority of the internet isnt running on it anymore. It's too old, there's too many vulnerabilities and inefficiencies, vs wasm is sandboxed by nature, you dont even need to host a vm anymore, just host your wasm at a fraction of the cost. That's actually the whole premise of Wasmer, because it's so cheap to host a site, that they literally offer it for free, because you share a server with everyone else, without compromising safety. As compute gets more expensive and AI resource demands increases, vm prices will go up and people will look for an alternative.

HTML is old, sure, but so was Fortran and Basic? JavaScript is synonymous with the internet, but so was basic? Linux is universal, but so was IBM... It's tech, the moment something new is architecturally better, the old guard just needs to show weakness and people switch and with AI-driven attacks and pen-testing, more and more critical issues are showing up, like Node.js and PHP the other day... When people realize that their long-standing trust in these products, were founded on a false sense of security, something newer and safer by design makes alot more sense.

Collapse
 
benrrr profile image
Brrrrr •

JS being JS

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

How not to love it 😅

Collapse
 
jamescarter11 profile image
James Carter •

Great explanation! JavaScript's type coercion can be confusing, especially for beginners, but examples like these make the underlying rules much easier to understand. I also appreciate the distinction between {} as an empty block and an object literal. Definitely a fun reminder to pay attention to context when writing JavaScript!

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Oh, absolutely! 😄 These days, most of us use TypeScript, and it sometimes feels like we're pretty well protected against JavaScript's weirdness in everyday development. But you never know, over the years, you end up working on all kinds of projects!

Collapse
 
alexcodebytes profile image
Oleksandr •

The {} being parsed as an empty block instead of an object literal is the classic gotcha. My favorite is [] + [] giving an empty string, which is technically correct but feels wrong every time. Great explanation of the parser's role.

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Exactly! 😂 It all makes perfect sense once you understand how it works, but it still feels so wrong! XDDD

Collapse
 
alexcodebytes profile image
Oleksandr •

The 'feels so wrong' part is why I love this language. It's technically correct, logically consistent, and completely counterintuitive. It's the perfect combination for a programming language.

Thread Thread
 
sylwia-lask profile image
Sylwia Laskowska •

Exactly! You can definitely tell this language was created in just 10 days! 😂

Collapse
 
sgaggjhkjh profile image
Arjun Sharma •

The block versus object distinction is the clearest part, because it explains why the same characters change meaning with position. Do you think teaching this parsing step first would help beginners treat coercion less as magic and more as a predictable sequence?

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Probably yes! 😄 But honestly, I'd teach them TypeScript first! :D

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani • • Edited

The sneaky part is +[] detouring through "" on its way to 0, same reason an empty form field sails past a Number() check

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Exactly! 😂 JavaScript has been turning empty things into zero for 30 years, and we're still finding new ways to get surprised by it.

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

Thanks, Sylwia. That empty to zero path keeps showing up in the places you least expect it.

Collapse
 
mp3sss31 profile image
mp3sss •

Appreciate the 'weird but spec-consistent' framing — the danger in real apps isn't the quirk itself, it's the implicit conversion happening where you least expect it. In Electron IPC I've seen "ok" and 0 arrive at the main process because a renderer sent a checkbox value that went through Number() implicitly, and the fix is to never let a value cross the process boundary without an explicit type check — the same instinct as wrapping {} + [] in parens so the intent can't be re-parsed. Reading the spec beats memorizing WTF lists, since the WTF list is just the spec's edge cases in disguise.

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Exactly! 😄 And that's a great real-world example of why implicit coercion can be more than just a funny JavaScript quirk. It's one thing to laugh at {} + [] in the console, and quite another to debug unexpected values in a real application! 😂 Explicit type checks at system boundaries are definitely a good habit. And yes, understanding why JavaScript behaves this way is much more useful than memorizing a list of weird expressions!

Collapse
 
codingwithjiro profile image
Elmar Chavez •

LOL. I remembered when I was first learning JavaScript and made a site out of it:

https://javascript-fundamentals-jiro.netlify.app/#variables

The funny thing is, I was so focused on remembering all these nuances the first time I saw them. I thought to myself, if I forget even one of them and I accidentally implemented it in my project, it would give me a hard time in the future. But it turns out, I never got to that point. Now I see them as just nice to know. Still fun to learn them though.

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Hahaha, I had a look at your website! 😄 It's a nice collection of JavaScript fundamentals! Luckily, these days we have linters, TypeScript, and other tools, so we don't have to memorize every little detail. And things like the ones in my article are really more fun trivia than something you actually need to know by heart!

Collapse
 
argumentmoney8117 profile image
ArgumentMoney8117 •

The block-versus-object-literal distinction is the part that made this click for me. Once that parsing difference is clear, the rest of the coercion steps follow naturally instead of looking like magic.

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Exactly! 😄 Once you realize JavaScript isn't even treating {} as an object in that context, the whole thing starts to make sense. Still looks completely ridiculous at first glance, though! 😂

Collapse
 
bruce_xu profile image
Bruce Xu •

Great breakdown — the statement-position parsing quirk is the part that always trips people up. I got tripped up by this question during an interview.

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Hahaha, I got asked something similar in an interview once! I actually knew the answer, but they rejected me anyway 😂

Collapse
 
effessdev profile image
EffessDev • • Edited

This is why I always write everything explicitly 😅 It's not a problem as long as we avoid it right?

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Exactly! That's one thing! 😅 I also use TypeScript and linters to keep me (or my coding agent) in check whenever we get a little careless. Do you use TypeScript too?

Collapse
 
effessdev profile image
EffessDev • • Edited

I only use TypeScript (I literally forgot JavaScript lol), and I'd never do something like {} + [] (too risky 😬😅)

Thread Thread
 
sylwia-lask profile image
Sylwia Laskowska •

Hahaha, I can't even imagine where or why I'd ever need to use something like that! 😂

Collapse
 
chebit profile image
CheBit •

Interesting, I never noticed these things before, but I watched it out of curiosity after seeing it.

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Hahaha, we used to joke about stuff like this all the time at work, back in the pre-TypeScript days! :D

Collapse
 
pavel6625 profile image
Pavel6625 •

Okay, now I have a reason to move to TypeScript...

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Good call! 😂 Just remember, TypeScript won't be there to save you at runtime!

Collapse
 
marko_kseppnen_6250a7f profile image
Mr Smithnen •

Hehe 😆

Thanks for the nice read 👍

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

😊

Collapse
 
ctaxnagomi profile image
CTAXNAGOMI •

Love reading this !!

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Thanks 🥰

Collapse
 
javierolazaran profile image
Javier Olazarán •

This is the longest "it's not a bug, it's a feature" I've ever read.

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Hahaha, I love this comment! 😂 But if this is the longest explanation of "it's not a bug, it's a feature" you've ever seen, I can already tell you've never worked on my project! XDDD

Collapse
 
andychiare profile image
Andrea Chiarelli • • Edited

This reminds me of an old articles of mine: dev.to/andychiare/-in-defense-of-j... 🙂

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Ah, beautiful! 😂 JavaScript has been a reliable source of content for DEV since at least 2019!

Collapse
 
leob profile image
leob •

Wow! The fact that {} isn't an object at all, and that the + is unary - I didn't see that one coming! Might be logical "when explained after the fact", but I'm finding this truly bizarre ...

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Exactly! 😂 Just because you understand the logic behind it doesn't make it any less bizarre! I mean... well, it's JavaScript. XDDD

Collapse
 
kling4ai-production profile image
Kling4 AI •

Type coercion rules around ToPrimitive and valueOf are consistent once you read the ECMAScript spec, but they still catch people off guard in daily practice.

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Exactly! 😄 It all makes perfect sense once you understand the rules, but it can still catch you by surprise! 😂

Collapse
 
udondan profile image
Daniel Schroeder •

If you haven't seen it yet, y'all have a look at jsfuck.com

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

HAHAHA I'm crying 🤣

Collapse
 
mohamed_mahmoud_32383bd38 profile image
Mohamed Mahmoud •

The most important question here is: why do we love JavaScript? 😂😂

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Stockholm syndrome, no doubt about it! 😂😂😂

Collapse
 
erfanju profile image
AFMEI •

You write a great post. I have learn a lot from it

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Thanks a million ☺️

Collapse
 
mohizare profile image
Mohammad Zare •

how about {} - [] 😁

Collapse
 
sylwia-lask profile image
Sylwia Laskowska •

Obviously, the only correct and legitimate answer is -0! 😂

Collapse
 
kling4ai-production profile image
Kling4 AI •

Great explanation! The distinction between block statement parsing and object literal evaluation is such a classic source of confusion here. Once people realize that {} at the start of a statement is interpreted as an empty block rather than an object literal, the type coercion logic actually follows clear specification rules.

Collapse
 
blenser4 profile image
Brock Lenser •

The block versus object explanation is the part that finally made this click for me. Once you see the parsing context, the result stops looking random and starts looking like a consistent rule.