Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 1 + '1' = '11' and 1 - '1' = 0 in JavaScript (Coercion)? [duplicate]

Tags:

javascript

This seems quite obvious in its logic (a string can't subtract) but I would like to know how this decision is taken in the underlying execution of JavaScript. How exactly are coercion rules being applied here?

like image 360
Nandeep Mali Avatar asked Sep 17 '14 14:09

Nandeep Mali


People also ask

What is type coercion in JavaScript?

Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers).

Why === is false in JavaScript?

Because == (and === ) test to see if two objects are the same object and not if they are identical objects.

Why is 0 == [] in JS?

In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.

What will be the result of console log 0 === 0 ')?

console. log( 0 == '0'); javascript uses coerceing and converts both to number and compares . Now 0==0 so true is returned .


1 Answers

- is defined in terms of ToNumber, whereas + has an extra clause for strings (emphasis mine):

11.6.1 The Addition operator ( + )

The addition operator either performs string concatenation or numeric addition.

The production

AdditiveExpression : AdditiveExpression +  MultiplicativeExpression 

is evaluated as follows:

  1. Let lref be the result of evaluating AdditiveExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating MultiplicativeExpression.
  4. Let rval be GetValue(rref).
  5. Let lprim be ToPrimitive(lval).
  6. Let rprim be ToPrimitive(rval).
  7. If Type(lprim) is String or Type(rprim) is String, then
    • Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)

[...]

like image 131
Zeta Avatar answered Sep 28 '22 06:09

Zeta