In this article, we are going to learn if a number is positive, negative, or zero, for numerous mathematical operations and conditional statements in JavaScript. It is critical to know if a given number is positive, negative, or zero. This article provides a straightforward approach in JavaScript that lets you determine whether a given number belongs to one of these groups.
Several methods can be used to Check if a number is Positive, Negative, or Zero.
Table of Content
We will explore all the above methods along with their basic implementation with the help of examples.
Approach 1: Using Switch Statement
In this approach, we are using a switch statement to check a number’s sign (positive, negative, or zero) based on Math.sign() method, this method is used to know the sign of a number, indicating whether the number specified is negative or positive.
Syntax:
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
. . .
case valueN:
statementN;
break;
default:
statementDefault;
}
Example: In this example, we are using the above-explained approach
function numberChecking(num) {
switch (Math.sign(num)) {
case 1:
console.log( "The number is Positive" );
break ;
case -1:
console.log( "The number is Negative" );
break ;
default :
console.log( "The number is Zero" );
}
} numberChecking(12); // Output: Positive numberChecking(-1); // Output: Negative numberChecking(0); // Output: Zero |
The number is Positive The number is Negative The number is Zero
Approach 2: Using if-else Statements
In this approach we are using the if-else or conditional statement will perform some action for a specific condition. If the condition meets then a particular block of action will be executed otherwise it will execute another block of action that satisfies that particular condition.
Syntax:
if (condition) {
// Executes this block if
// condition is true
}
else {
// Executes this block if
// condition is false
}
Example: In this example, we are using the above-explained approach.
const number = prompt( "Enter a number" );
if (number > 0) {
console.log( "The number is positive" );
} else if (number < 0) {
console.log( "The number is negative" );
} else {
console.log( "The number is zero" );
}; |
Output:
Approach 3: Using Ternary Operator
The ternary operator in JavaScript is an efficient one-line conditional statement that evaluates an expression and returns one of two defined values depending on a specific condition.
Syntax:
condition ? value if true : value if false
Example: In this example, we are using the above-explained approach.
function checkNumberSign() {
const input = prompt( "Enter a number:" );
const number = Number(input);
if (isNaN(number)) {
console.log( "Invalid input. Please enter a valid number." );
} else {
const result =
number === 0 ? "The number is zero." :
number > 0 ? `${number} is positive.` : `${number} is negative.`;
console.log(result);
}
} // Call the function to start the program checkNumberSign(); |
Output: