
In many languages like JavaScript, values can automatically convert (or coerce) from one type to another depending on what the operator expects.
When you write "11" - 1, JavaScript thinks:
“Subtraction only makes sense for numbers, so I’ll try to turn the string
"11"into a number.”
So it converts "11" → 11, and then does:
11 – 1 = 10
✅ Result: 10
➕ But Why "11" + 1 = "111"?
Now let’s look at the plus sign (+).
In JavaScript, + is special — it can mean addition or string concatenation.
When either side of + is a string, JavaScript assumes you’re doing text concatenation, not math.
So:
“11” + 1 → “11” + “1” → “111”
✅ Result: “111”
This behavior is not a bug — it’s part of how JavaScript (and some other weakly typed languages) handle mixed data types.
🧩 Why Does This Matter?
This tiny difference can lead to unexpected bugs in real code. For example:
const a = "10";
const b = 5;
console.log(a + b); // "105" (Oops!)
console.log(a - b); // 5 (Wait, what?)
If you meant to do numeric math, the correct way is:
Number(a) + b; // 15
or in modern JavaScript:
+a + b; // 15 (the unary + operator converts to number)
🧮 What About Other Languages?
Let’s compare how a few popular languages handle this:
| Language | "11" - 1 | "11" + 1 | Notes |
|---|---|---|---|
| JavaScript | 10 | "111" | Implicit type coercion |
| Python | ❌ TypeError | ❌ TypeError (unless you convert manually) | Explicit conversion required |
| Java | ❌ Compile error | "111" (only with + and automatic string conversion) | + concatenates strings |
| PHP | 10 | "111" | Behaves similar to JavaScript |
So, depending on the language, + and - can have totally different meanings.
💡 Key Takeaways
-forces numeric conversion —"11" - 1becomes11 - 1.+favors string concatenation —"11" + 1becomes"11" + "1".- Always be explicit about conversions to avoid surprises.
- When in doubt, use:
Number("11") + 1; // 12 String(11) + 1; // "111"
✨ Final Thought
This tiny example perfectly shows the beauty and quirks of programming languages.
Sometimes, the difference between "11" - 1 and "11" + 1 isn’t about math — it’s about how computers think about data.
Understanding these small details makes you a sharper, more intentional coder — and helps you avoid those “Wait, what just happened?” moments!
#JavaScriptTips #SalesforceJavaScriptTips #SalesforceTinyTips #Salesforce