totn JavaScript

JavaScript: Math sign() function

This JavaScript tutorial explains how to use the math function called sign() with syntax and examples.

Description

In JavaScript, sign() is a function that is used to return a value indicating the sign of a number. Because the sign() function is a static function of the Math object, it must be invoked through the placeholder object called Math.

Syntax

In JavaScript, the syntax for the sign() function is:

Math.sign(number);

Parameters or Arguments

number
The number to test for its sign.

Returns

The sign() function returns 1 if the number is greater than 0.

The sign() function returns 0 if the number is equal to 0.

The sign() function returns -1 if the number is less than 0.

Note

  • Math is a placeholder object that contains mathematical functions and constants of which sign() is one of these functions.

Example

Let's take a look at an example of how to use the sign() function in JavaScript.

For example:

console.log(Math.sign(32));
console.log(Math.sign(0));
console.log(Math.sign(-4));

In this example, we have invoked the sign() function using the Math class.

We have written the output of the sign() function to the web browser console log, for demonstration purposes, to show what the sign() function returns.

The following will be output to the web browser console log:

1
0
-1

In this example, the first output to the console log returned 1 since the value 32 is a number greater than 0 (ie: a positive number).

The second output to the console log returned 0 since the value 0 is equal to 0.

The third output to the console log returned -1 since the value -4 is a number less than 0 (ie: a negative number).