Here are a couple of examples showcasing my code. Let's start with the first one:
console.log([4] + 10); //"410"
It is commonly known that the addition operator can only work with numbers and strings. Therefore, in this case, [4]
needs to be converted into either a number or a string. When attempting this conversion, JavaScript will call on either the valueOf()
or toString()
method. By default, valueOf()
returns an array, so JavaScript opts for the toString()
method which converts the complex data type into a string. However...
Let's explore the second example now:
console.log(10 - [4]); //6
I find it puzzling how valueOf()
manages to transform an array into a number when its default behavior is returning an array. What exactly happens here?