Lesson 16: Mastering JavaScript String Concatenation with Binary +

manoj ymkmanoj ymk
5 min read

๐Ÿ”ธ Basic Behavior

In JavaScript:

  • The binary + operator behaves differently based on operand types.

  • If either operand is a string, it converts the other to a string and performs concatenation.

  • If both are numbers, it adds them.

console.log(1 + 2);         // 3 โ†’ number + number = addition
console.log('1' + 2);       // "12" โ†’ string + number = string concatenation
console.log(2 + '1');       // "21" โ†’ number + string = string concatenation
console.log(2 + 2 + '1');   // "41" โ†’ (2 + 2 = 4) โ†’ 4 + "1" = "41"
console.log('1' + 2 + 2);   // "122" โ†’ "1" + 2 = "12", "12" + 2 = "122"

๐Ÿ”ธ Diagram: Execution Timeline

Expression:  2 + 2 + '1'
Step 1:      2 + 2 = 4         โ†’ [number addition]
Step 2:      4 + '1' = "41"    โ†’ [string concatenation]

๐Ÿ”ธ Operator Precedence

  • + is left-to-right associative.

  • Evaluation order impacts result if types differ.


๐Ÿ”น 2. Fill Any Gaps

๐Ÿ”ธ Hidden Rules & Internal Mechanics

  1. ToPrimitive Coercion

    • Before concatenation, JavaScript calls ToPrimitive() on non-primitive types.

    • If an object is used:

        console.log({} + "test");   // "[object Object]test"
        console.log([] + 1);        // "1"
      
  2. Binary + is the only arithmetic operator that performs string concatenation.

     console.log(4 - "2");   // 2 โ†’ string converted to number
     console.log("4" * "2"); // 8 โ†’ both converted to numbers
    
  3. Falsy Confusion

     console.log(false + 1); // 1
     console.log(true + "1"); // "true1"
    
  4. Null/undefined edge cases

     console.log(null + "a");     // "nulla"
     console.log(undefined + "a");// "undefineda"
    

๐Ÿ”ธ Browser-Specific Quirk

Different browser dev tools sometimes display intermediate coercion steps differently, but the logic remains standardized via ECMAScript ToPrimitive.


๐Ÿ”น 3. Challenge Me Deeply

๐ŸŸข Basic

  1. What is the output?

     console.log("3" + 4 + 5);
    
  2. Predict this:

     console.log(5 + 4 + "3");
    
  3. Why does this happen?

     console.log([] + 1 + 2);
    
  4. Guess the result:

     console.log({} + "hello");
    

๐ŸŸก Intermediate

  1. What does this print and why?

     console.log(true + false + "5");
    
  2. Output?

     console.log(10 + null + undefined);
    
  3. Spot the bug:

     jsCopyEditlet result = "Result: " + 10 - 2;
     console.log(result);
    
  4. Predict:

     console.log("a" + + "b");
    

๐Ÿ”ด Advanced

  1. Debug and explain:

     let a = 1;
     let b = "2";
     console.log(a + +b); // What's happening here?
    
  2. Tricky coercion:

console.log([] + {});       // ?
console.log({} + []);       // ?

๐ŸŽฏ Bonus: Mind-Bending

  1. What will this log and why?
console.log([] + [] + 'foo' + []);

๐Ÿ”น 4. Interview-Ready Questions

๐Ÿ”ธ Concept Questions

  • Explain how JavaScript decides whether to add or concatenate when using +.

  • What is type coercion? How does it relate to the + operator?

  • Why is the result of 2 + 2 + "2" different from "2" + 2 + 2?

๐Ÿ”ธ Scenario-Based

  • Youโ€™re debugging a UI where user input values are concatenated instead of summed. Whatโ€™s going wrong?

      let num1 = prompt("Enter a number:");
      let num2 = prompt("Enter another:");
      alert("Sum is: " + num1 + num2); // Bug?
    

๐Ÿ”ธ Debugging Style

  • You get "undefined5" as a string in logs. What kind of issue might this suggest in your code?

โœ… Interview Green Flags

  • You use Number() or parseInt() to ensure numeric addition.

  • You mention ToPrimitive or coercion rules confidently.

๐Ÿšฉ Red Flags

  • Relying on implicit coercion for complex expressions.

  • Not understanding that + behaves differently than other math ops.


๐Ÿ”น 5. Real-World Usage

๐Ÿ”น Common in Frontend Development

  • Template rendering:

      const name = "Alice";
      const message = "Hello, " + name + "!";
    
  • Form input handling:

      const num1 = Number(document.getElementById("n1").value);
      const num2 = Number(document.getElementById("n2").value);
      alert("Sum = " + (num1 + num2));
    

๐Ÿ”น Frameworks & Libraries

  • React / Vue: Dynamic strings in JSX or template bindings.

  • Logging Libraries: Concatenating log messages.


๐Ÿ”น 6. Remember Like a Pro

๐Ÿ”ธ Mnemonic

๐Ÿง  โ€œString wins in +โ€
If there's a string, the + becomes glue.

๐Ÿ”ธ Visual Cheat Sheet

ExpressionResultWhy
'2' + 1"21"String + number = string
2 + '1'"21"Number + string = string
2 + 2 + '1'"41"Number + number, then + string
'1' + 2 + 2"122"String first, rest becomes string
6 - '2'4Subtraction forces numbers

๐Ÿ”น 7. Apply It in a Fun Way

๐Ÿงฉ Mini Project: Smart Calculator with Type Safety

Goal: Create a calculator that behaves correctly when summing user inputs from forms.

๐Ÿ”จ Steps:

  1. Create 2 <input> fields for numbers.

  2. A <button> to trigger calculation.

  3. Display:

    • Sum (real addition)

    • Concatenation (forced string)

  4. Use Number() to fix bugs.

๐Ÿ” Extension:

  • Auto-detect and warn if input looks like a string.

  • Add a toggle to view evaluation steps (debug view).


โž• (Bonus) Open Source & Pro Tips

๐Ÿ”Ž Projects using + Concatenation

  • Lodash: Internal string formatting utilities.

  • Chalk: String manipulations for CLI colors.

  • React DevTools: Debugging label formats.

๐Ÿ’ฅ Common Mistakes

  • Not wrapping expressions:

      "Result: " + a + b   // Wrong if a and b are numbers!
      "Result: " + (a + b) // Correct
    

โšก Performance Tip

  • For large string joins in loops, prefer .join() over repeated + (V8 optimizes but still consider readability/perf tradeoff).
0
Subscribe to my newsletter

Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

manoj ymk
manoj ymk