Using the Unary + Operator Before a String and Concatenating It in JavaScript – Asked in a Deloitte Interview.


Understanding the Code Step by Step

The given JavaScript snippet contains a tricky expression that involves string concatenation (+) and unary plus (+). Let’s break it down the code expression.


Step 1: Understanding the Expression

var str = "abc" + +"def";

Let’s analyze the right-hand side of the assignment:

"abc" + +"def"

This consists of:

  1. string "abc"
  2. string concatenation (+) operation
  3. unary plus (+) applied to "def"


Step 2: Evaluating the Unary Plus (+)

+"def"
  • The unary plus (+) is a JavaScript operator that attempts to convert its operand into a number.
  • Here, "def" is a string that does not represent a valid number.
  • When JavaScript tries to convert "def" to a number using +, it results in:

NaN // Not a Number

    So, "abc" + +"def" is equivalent to:

    "abc" + NaN

    Step 3: Evaluating the String Concatenation

    "abc" + NaN
    • The + operator, when used with a string, performs string concatenation rather than arithmetic addition.
    • "abc" is a string, and NaN is coerced into its string representation, which is "NaN".
    • So, "abc" + NaN evaluates to:

    "abcNaN"

      Step 4: Assigning the Value

      var str = "abcNaN";

      Now, str holds the value:

      "abcNaN"

      Step 5: Logging the Output

      console.log(str);

      Console Output:

      abcNaN

      🔍 Key Takeaways

      1. The unary plus (+) operator attempts to convert "def" into a number but fails, resulting in NaN.
      2. The + operator between a string ("abc") and NaN leads to string concatenation, resulting in "abcNaN".

      ✨ Conclusion

      This code snippet is a classic example of JavaScript’s type coercion!
      It demonstrates how the unary plus (+) operator attempts type conversion and how concatenation works when dealing with NaN.


      ✔ Final Answer:

      C) abcNaN

      🔹 This question appeared in the Deloitte 1st round of interview, testing the candidate’s knowledge of string concatenation and the unary plus (+) operator in JavaScript.

      Post a Comment

      Previous Post Next Post