Learn how to check if a number is positive or negative in JavaScript. Use if statements and comparison operators to determine if a number is greater than or less than zero. You can also add nested if…else statements to check if the number is actually a number.
if (num > 0) {
// code to execute if number is positive
} else if (num < 0) {
// code to execute if number is negative
} else {
// code to execute if number is zero
}
For example check if the number is positive or negative JavaScript
Simple example code.
Check Number Type with if…else if…else
You can check if a number is positive or negative in JavaScript using an if statement and the greater than (>) or less than (<) operators.
let num = 5;
if (num > 0) {
console.log("Number is positive");
} else if (num < 0) {
console.log("Number is negative");
} else {
console.log("Number is zero");
}
You can use nested if...else
statements in JavaScript to check the type of a number.
let num = 5;
if (typeof num === "number") {
if (num > 0) {
console.log("Number is positive");
} else if (num < 0) {
console.log("Number is negative");
} else {
console.log("Number is zero");
}
} else {
console.log("Not a number");
}
Output:
Comment if you have any doubts or suggestions on this JS number topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version