How does the "+" operator work in Javascript?

Asked

Viewed 165 times

6

Recently I had seen on the website of MDN Web Docs that it was possible to convert a String in a Number even in the example below:

let n1 = "10";
console.log(typeof n1); //=> string ("10")

The variable n1 holds the value "10", who’s kind string. But if you try to do this:

let n1 = "10";
console.log(typeof +n1) //=> number (10)

The variable n1 becomes a value of the type number. The problem is that if instead of displaying the variable type n1, and show the conversion, the variable is no longer number, and yes string:

let n1 = "10";
console.log(n1 + 10 + " " + typeof n1); // "1010" (string)
console.log(+n1 + 10 + " " + typeof n1) // "20" (tipo string)

How is this possible? In the last example it returns the type string, then it was to concatenate +n1 + 10 and give the same result as the first example that is 1010, but not it adds up the two values and gives the result 20, but it does not behave as a value of type number is a value of the kind string.

Can someone please explain to me if this is a bug or if I don’t understand something right? I know there are other ways to turn something into certain things but I want to focus on that problem.

  • On these tests of yours at the end of the question, note that the operations are evaluated from left to right. Then the first case starts with string + number, and the second with number + number.

  • Not directly related, but in some cases, use + to convert string to number can give different results from parseInt and parseFloat (which are the functions I prefer to use instead of +). See more details at https://answall.com/a/410229/112052

1 answer

11

Not a bug. This is something expected from the language. The operator + is specified so that it can act as a unary operator or as a binary operator.

Operator + unary

If you are in the context of unary operator, that is, is operating on only one its value, its only function is to convert the [single] operand to the primitive type number. See some examples:

console.log(+ false); // 0
console.log(+ true); // 1
console.log(+ "10"); // 10

When acting as an unary operator, the + acts similarly to the constructor Number, which, when called as a function, converts the first argument to the numerical type.

Operator + binary

The + can also play the role of a binary operator. In that case, it operates on two values. In this sense, the + can have two different functions, depending on the type of the two operands:

  • Carry out the summing up two values (addition); or:
  • Carry out the concatenation two-string.

For this to happen, some rules are established in order to establish when the values will be added or the values concatenated. It occurs like this:

  • First, the operator converts the two operands to primitive values. After that, it will follow one of the two modes:
    1. String mode: If either of the two operands is a string, the other operand will be converted to the type string corresponding. The two values will be concatenated and returned as string.
    2. Numerical mode: Otherwise (none of the operands is string), it will convert both operators to type number. The two values will be subsequently summed and returned as number.

You can see it working below:

// Modo string (caso um dos operandos seja string):
console.log(1 + "5"); // "15"
console.log("5" + 1); // "51"
console.log(false + "y"); // "falsey"

console.log('---');

// Modo numérico (caso nenhum dos operandos seja string):
console.log(false + 1); // 1 (false será convertido para 0)
console.log(true + 1); // 2
console.log(5 + []); // 5 ([] é convertido para 0)


In the last example of the question, the evaluation of operators follows a rule of precedence, which can be consulted here.


Reference:

  • Javascript for impatient programmers, § 12.2.
  • 2

    Every time I see an array being added with something I remember this: https://www.destroyallsoftware.com/talks/wat

Browser other questions tagged

You are not signed in. Login or sign up in order to post.