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
Let’s analyze the right-hand side of the assignment:
This consists of:
- A string
"abc"
- A string concatenation (
+
) operation - A unary plus (
+
) applied to"def"
Step 2: Evaluating the Unary Plus (+
)
- 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:
So, "abc" + +"def"
is equivalent to:
Step 3: Evaluating the String Concatenation
- The
+
operator, when used with a string, performs string concatenation rather than arithmetic addition. "abc"
is a string, andNaN
is coerced into its string representation, which is"NaN"
.- So,
"abc" + NaN
evaluates to:
Step 4: Assigning the Value
Now, str
holds the value:
Step 5: Logging the Output
Console Output:
🔍 Key Takeaways
- The unary plus (
+
) operator attempts to convert"def"
into a number but fails, resulting inNaN
. - The
+
operator between a string ("abc"
) andNaN
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.