What is Math.sign in JavaScript ?
Math.sign
The Math.sign method is used to find the positive or negative state of a number. This method will return:
1if the number passed is a positive number.-1if the number passed is a negative number+0if the number passed is +0-0if the number passed is -0NaNon all other cases
console.log("Math.sign of 10", Math.sign(10));console.log("\n---------\nMath.sign of -10", Math.sign(-10));console.log("\n---------\nMath.sign of 0", Math.sign(0));console.log("\n---------\nMath.sign of 0", Math.sign(-0));console.log("\n---------\nMath.sign of undefined", Math.sign());console.log("\n---------\nMath.sign of null", Math.sign(null));
If the argument passed to the sign function is not a number, then the value will be implicitly converted to a number type.
console.log("---------\nMath.sign of '10'", Math.sign('10'));console.log("\n---------\nMath.sign of '-10'", Math.sign('-10'));console.log("\n---------\nMath.sign of 'abc'", Math.sign('abc'));
Using Math.sign
Let’s say we have an array of elements, and we need to print each element and its positive/negative state. Take a look at the code below:
let arr = [1, 2, -3, 0, -4];for(let i = 0,l = arr.length; i < l; i++){if(Math.sign(arr[i]) < 0){console.log("Number is ", arr[i], " -> Negative")} else {console.log("Number is ", arr[i], " -> Positive")}}