Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding strings in JavaScript "1" + - "2" == "1-2"

I accidentally typed the following JavaScript statement "1" + - "2" and I have the result "1-2". I am not sure why the minus sign was treated as a string rather than causing a syntax error.

I tried to search, but I did not get the answer I wanted.

Why the minus sign was treated as a string? it there online reference I can look at? thanks

like image 499
aljordan82 Avatar asked Nov 07 '13 19:11

aljordan82


People also ask

How do I sum a string in JavaScript?

Use the addition (+) operator, e.g. Number('1') + Number('2') . The addition operator will return the sum of the numbers.

Can we add two strings in JS?

JavaScript, like any good language, has the ability to join 2 (or more, of course) strings. How? We can use the + operator. I generally recommend the simplest route (which also happen to be the faster) which is using the + (or += ) operator.

How do you add two variables in JavaScript?

Basic JavaScript Addition var x = 1; var y = 2; var result = x + y; The result is "3" in this simple example. Add numbers in JavaScript by placing a plus sign between them.


2 Answers

Simple: - "2" evaluates to -2 because unary - coerces its operand to a number, which is precisely the behavior defined in the ECMA-262 spec.

11.4.7 Unary - Operator

The unary - operator converts its operand to Number type and then negates it. Note that negating +0 produces −0, and negating −0 produces +0.

The production UnaryExpression : - UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.
  2. Let oldValue be ToNumber(GetValue(expr)).
  3. If oldValue is NaN, return NaN.
  4. Return the result of negating oldValue; that is, compute a Number with the same magnitude but opposite sign.

Then it's just a matter of string concatenation: "1" + (-2) evaluates, unsurprisingly, to "1-2". By this point it should comes as no surprise that the + is a string concatenation (and not an addition) operator in the context because that's what the spec says.


TL;DR

Because, as always, that's the behavior required by the spec.

like image 193
Matt Ball Avatar answered Sep 30 '22 06:09

Matt Ball


The original

"1" + - "2"

Is parsed as

"1" + ( - "2" )

The - here converts the "2" to a number and negates it, so - "2" evaluates to -2. So this becomes:

"1" + (-2)

Here, the + causes the -2 to be converted to a string, "-2", and then does simple string concatenation.

like image 40
p.s.w.g Avatar answered Sep 30 '22 05:09

p.s.w.g