5
I have a question about the operator +
.
In this answer on the operator, the following was said:
The
+
can also play the role of a binary operator. In that case, operates on two values. In this sense, the+
may 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.
...
- First, the operator converts the two operands to primitive values. After that, it will follow one of the two modes:
- 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.- Numerical mode: Otherwise (none of the operands is string), it will convert both operators to type
number
. Both values will be added later and returned as number.
I noticed some behaviors. The operator +
"it seems" that invokes the function valueOf
whenever it is present within an object. See below:
function User() {
return {
valueOf: () => 'Brendam'
}
}
const result = new User() + new User()
console.log(result)
As seen above, the +
did something more than I expected. But it didn’t end there. The same behavior happens if we try to use this operation to convert a literal object that has the same method, but returns a number. If it returns a string, we receive NaN
as a result:
let obj = {
valueOf: function() {
return 'Brendam'
}
}
let obj2 = {
valueOf: function() {
return 10;
}
};
console.log(+obj) // NaN
console.log(+obj2) // 10
I confess that I was very confused by the use of this operator:
- Why
+
invokes thevalueOf
? What is the relationship between them? - Only this operator does this? Or does the same behavior repeat for some other operator?
bizarre things from
javascript
, I can’t imaginenew User() + new User()
in java, c, c++ or c# for example :D– Ricardo Pontual
@Ricardopunctual would be so simple if I made just one exception...
– Cmte Cardeal
because it is, javascript deceives us, not error in many situations, but returns something difficult to understand
– Ricardo Pontual