Voricles
Voricles

Reputation: 11

What is the explanation for typeof a where var a = 2 + [] is string?

I am looking at the typeof a where var a = 2 + []. I expected the answer to be 2 of type number but I am getting '2' of type string. However, when I evaluate var b = 2 - [], I get the value to be 2 of type number. Can somebody assist me to understand this behavior.

const arr = [];

const a = 2 + arr;
console.log(a); // '2'
console.log(typeof a) // string

const b = 2 - arr;
console.log(b) // 2
console.log(typeof b); // number

//I expected the value a to be 2 of type
//number just as b

//If I toggle the boolean value of arr,
//both a and b evaluates to 2 of
//type number

Upvotes: 0

Views: 57

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074198

+ with two operands is the "addition operator," which may do mathematical addition or string addition (concatenation) depending on its operands.

When any operand to + is an object, the JavaScript engine converts the object to a primitive. In your case, the array is an object. Converting an array to a primitive yields a string (as though you'd called their toString method, which basically does .join()). So then the + operator is dealing with a number and a string. When either operand is a string, + converts the other operand to string, and so you get "2" as the result. That is:

  • 2 + [] becomes
  • 2 + "" which becomes
  • "2" + "" which is
  • "2"

- with two operands is the "subtraction operator" and it's very different. It's only for math, it doesn't have any string meaning. That means it converts its arguments to numbers. Converting an array to number involves first converting it to a string, then converting the string to a number. [] becomes "" which converts to 0. So:

  • 2 - [] becomes
  • 2 - "" which becomes
  • 2 - 0 which is
  • 2

Upvotes: 2

Related Questions