JavaScript + and - Operators: Understanding Type Coercion

😄 JavaScript really said: “So… you thought you understood +?” Let’s clear the confusion properly — no vibes, just fundamentals 👇 🔹 Case 1: Number + Number 2 + 2 // 4 ✅ Simple math. No drama. 🔹 Case 2: Number + String 2 + "2" // "22" ⚠️ + becomes concatenation JS says: “Oh, you want strings? Say less.” 🔹 Case 3: String + String "2" + "2" // "22" 🧩 Pure concatenation. Expected. 🔹 Case 4: Minus operator (-) "22" - 2 // 20 💡 - forces numeric conversion If conversion fails → NaN (not magic, just math rules). 🧠 The real lesson + can add OR concatenate -, *, / only work with numbers JavaScript always tries type coercion Types matter more than intentions 😅 ❌ JavaScript isn’t confusing ❌ Logic isn’t broken ✅ Skipping the basics is. Memes make it funny. Fundamentals make it predictable. 😉 #JavaScript #WebDevelopment #Programming #TypeCoercion #JSBasics #LearnInPublic #Developers #Frontend #JavaScript #Notes #JavaScript #Developer #JavaScript #Mastery #JavaScript #umarhasnain

  • No alternative text description for this image

Js will concatenate strings when the + operator is used hence why "2" + "2" output "22" which is a string and not a number. When using the + operator on numbers it will do normal mathematical operations hence why 2 + 2 outputs 4. When it comes to "2" + "2" - "2", Javascript sees the - operator and knows instead of concatenation mathematical operations need to happen and converts the entire thing to numbers then does the operation of adding and subtracting, thus "2"+"2"-"2" outputs 20.

Simple rules - js used toPritimive() and try to convert in primitive . it uses valueOf for that . If didn't get primitive value then used toString(). If value is number then does calculation on number basic else try to convert into string and then do calculation. If + or any side is string then JS uses to string() If -,*,/ these type of operations JS used to number. If <,><=,>= . Js used toPritimive If === check types and value and directly return true or false If == then js used toPritimive()

Like
Reply

JavaScript really said, “I’ll try my best to make it work” 😅 Unlike Java and Python, where this would fail fast, JS leans on type coercion. Great breakdown — once the basics are clear, everything becomes predictable 👌

Like
Reply

JavaScript's quirky behavior with operators used to trip me up constantly until I really dug into how type coercion works behind the scenes.

Like
Reply

And this is why typescript was invented 😅

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories