Why is Math.sign([]) = 0, Math.sign([20]) = 1, and Math.sign([20, 30, 40]) = NaN?

GeniusGo

As Math.sign() accepts a number parameter or number as a string as per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign, why does it give the following results and how are the internal conversions taking place while giving these results?

console.log(Math.sign([])); // 0

console.log(Math.sign([20])); // 1

console.log(Math.sign([20, 30, 40])) // NaN

CertainPerformance

It expects to be passed a number. If a non-primitive is passed to it, it attempts to convert that non-primitive to a number first.

When arrays are converted to numbers, their values are first joined by , to create a string, and then the interpreter tries to turn that string into a number. So with

Math.sign([]);

the empty array is converted to the empty string, which is then turned into a number - and Number('') is 0, hence the result is 0.

With [20], this is joined into a string of '20', which is then turned into the number 20, whose sign is positive.

With [20, 30, 40], this is joined into '20,30,40', which cannot be turned into a number:

console.log(Number('20,30,40'));

So the output is NaN.

Best to always do explicit type casting when you aren't 100% sure of what the result of implicit type coercion will be.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related