Home > Back-end >  How does subtraction operator trigger an array-to-number conversion?
How does subtraction operator trigger an array-to-number conversion?

Time:09-21

Here are 2 examples of my code. The first one is:

console.log([4]   10); //"410" 

As far as I know, addition operator can work only with numbers and strings. So, firstly, [4] should be transformed into the number or string. When trying to convert an operand to a primitive data type, either valueOf() or toString() runs. By default, valueOf() returns an array, so this method is ignored. toString() is invoked. It converts the complex data type to a string. That's completely understandable for me, but...

What's going on in the second example?

console.log(10 - [4]); //6 

I don't get how valueOf() can transform array into the number if this method by default returns an array. What does occur here?

CodePudding user response:

It goes this way:

10 - [4]
10 - '4' // array to string
10 - 4   // implicit casting of all operands to number with minus operator
6        // result
  • Related