Why is the result of ('b'+'a'+ + 'a' + 'a').toLowerCase() 'banana'?
The unexpected outcome of ('b'+'a'+ + 'a' + 'a').toLowerCase()
hinges on + + 'a'
, which treats +'a'
as a unary plus, coercing 'a'
into a number. This fails, yielding NaN
. Consequently, the string 'b' + 'a' + NaN + 'a'
is created. Transformed to 'baNaNa'
and finally, .toLowerCase()
turns it into 'banana'
.
Diving into the unary plus and coercion
The first +
plays the role of a concatenation operator. The second +
(preceded by a space) acts as a unary plus operator which attempts to coerce the 'a'
string into a number. Since 'a'
doesn't resemble a number, it spits out NaN
.
What's happening?
- Space between
+
operators is paramount, seperating the unary plus from the concatenation plus. - Unary plus (
+
) takes precedence over concatenation. - Risk of introducing
NaN
when unary plus is used on non-numeric strings due to type coercion.
Operator precedence and JavaScript's talent show
JavaScript evaluates expressions from left to right, adhering to operator precedence rules. With various oeprand types (strings and numbers), JS showcases its type juggling skills to understand how to apply these operators.
Cases in point:
- String + String: Leads to string concatenation (
'1' + '1'
becomes'11'
). - Number + Number: Performs simple addition (
1 + 1
results in2
). - String + Number (or vice versa): Triggers type coercion ( thus
'1' + 1
gives'11'
).
Watch out for:
+'a'
, a ToNumber conversion error, ends up asNaN
.- Unintentional string concatenation due to string coercion when you expected arithmetic addition (
'5' + 5
results in'55'
).
Ensuring smooth sailings with optimization and good practices
Understanding and mindful application of type conversion is vital. Being aware of scenarios where type juggling can occur could save you from unanticipated results in your code.
Handy tips:
- Avoid implicit type conversion, be explicit with your intended types.
- When in doubt, use explicit conversion methods like
Number()
orString()
.
Good practices to adopt:
- Avoid unclear uses of
+
operator. - For string formation, consider template literals:
- Ensure operand types align with your anticipated operation.
Was this article helpful?