JavaScript's + Operator: A Deeper Look

Yesterday, I went deeper into one of the most confusing parts of JavaScript: "The + operator" At first glance, `+` looks simple. But unlike operators such as -, *, and /, JavaScript’s + has two possible meanings: - numeric addition - string concatenation And that is exactly what makes it tricky. My biggest takeaway was this: 1. When JavaScript sees a + b, it does not immediately assume numeric addition. 2. It first has to decide: - Should this be string concatenation? - Or should this be numeric addition? That decision is what makes "+" so different from operators like "-". For example: - "5" - 1 gives 4 because subtraction is numeric only. But: - "5" + 1 gives "51" because once JavaScript sees that one side becomes a string, it goes down the string concatenation path. I also learned that the real logic of + is deeper than the small operator section most people look at first. The actual mental model I now use is: 1. Convert both sides to primitives 2. If either primitive is a string: - convert both to strings - concatenate Otherwise: - convert both to numeric values - make sure the numeric types match - perform numeric addition That also led me into learning ToNumeric, which was another big insight. Before this, I mostly thought in terms of ToNumber, but ToNumeric is different: - ToNumber only gives a Number - ToNumeric can return either a Number or a BigInt That is why: - 1n + 2n works but - 1 + 2n throws a TypeError because JavaScript does not allow mixing Number and BigInt in that numeric path. The more I study coercion, the more I realise that JavaScript is not random at all. A lot of “weird” behavior starts making sense when you stop memorising examples and instead ask: - what operation is being performed? - what kind of value does it need? - which abstract operation is JavaScript using behind the scenes? That shift in mindset is making the language far more understandable for me. I’ve also been maintaining detailed notes on everything I’m learning. If anyone wants the deeper breakdown with examples and spec-based notes, I’ve uploaded them here: GitHub repo: https://lnkd.in/ephuZ-w6 Next, I’ll keep going deeper into coercion and loose equality. #JavaScript #TypeScript #WebDevelopment #SoftwareEngineering #ECMAScript #100DaysOfCode

  • graphical user interface, website

To view or add a comment, sign in

Explore content categories