Why is the result of ('b'+'a'+ + 'a' + 'a').toLowerCase() 'banana'?Uu DOo Nnf p Uu HW D Pt
27
I was just practising JavaScript when one of my friends came across this JavaScript code.
('b'+'a'+ + 'a' + 'a').toLowerCase()
The above code answers "banana".
Can anyone explain why?
javascript
New contributor
Harshvardhan Sharma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
|
show 3 more comments
1 Answer
active
oldest
votes
33
+'a' resolves to NaN ("Not a Number") because it coerces a string to a number, while the character a cannot be parsed as a number.
Adding NaN to "ba" turns NaN into the string "NaN" due to type conversion, gives baNaN.
And then there is an a behind, giving baNaNa.
To lowercase it becomes banana.
The space between + + is to make the first one string concatenation and the second one a unary plus (i.e. "positive") operator.
You have the same result if you use 'ba'+(+'a')+'a', which is equivalent to 'ba'+'NaN'+'a'.
-
5
'ba'+(+'a')+'a'is equivalent to'ba' + NaN + 'a'. The conversion to the string happens because'ba'beeing a string as the time when'ba' + NaNis performed.1 + + 'a' + 1isNaNbecause it is1 + NaN + 1and not1 + 'NaN' + 1which would result in1NaN1– t.niese 11 hours ago -
I believe there is some confusion between arithmetic operators and the unary plus in your answer. Technically speaking, the unary plus does not perform an arithmetic addition. – Gerardo Furtado 11 hours ago
-
@GerardoFurtado thanks. I made a typo when I wrote unary addition instead of unary plus. But it is a numeric-related operator nonetheless. – SOFe 11 hours ago
-
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Yeah but it is still an arithmetic operator as classified by MDN. – SOFe 11 hours ago
-
3@SOFe In my opinion the distinction is important. For better explaining, you have two different operators that use the same symbol (+). I'm using the ECMA specifications here: One is the addition operator (ecma-international.org/ecma-262/10.0/…). The other one is the unary operator (ecma-international.org/ecma-262/10.0/#sec-unary-plus-operator). They are different. To summarise, it doesn't "attempts to perform an arithmetic operation on a string", as you mentioned in your answer. – Gerardo Furtado 11 hours ago
|
show 2 more comments
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
+ + 'a'===NaN– The Reason 11 hours ago+"a"isNaN. – Gerardo Furtado 11 hours ago+'a'by itself and see what happens. – Some programmer dude 11 hours agocame across this javascript code--> Where ever this code was came across surely ought to have the explanation. – Krishna Prashatt 11 hours agotoLowerCase()... replace theb,a,a,awitha,b,c,d... which will surely make the result more apparent – Jaromanda X 10 hours ago