Javascript Program to Check if a number is Positive, Negative, or Zero

To understand this example, you should have the knowledge of the following JavaScript programming topics:


You will be using the if...else if...else statement to write the program.

Example 1: Check Number Type with if...else if...else

// program that checks if the number is positive, negative or zero
// input from the user
const number = parseInt(prompt("Enter a number: "));

// check if number is greater than 0
if (number > 0) {
    console.log("The number is positive");
}

// check if number is 0
else if (number == 0) {
  console.log("The number is zero");
}

// if number is less than 0
else {
     console.log("The number is negative");
}

Output

Enter a number: 0
The number is zero.

The above program checks if the number entered by the user is positive, negative or zero.

  • The condition number > 0 checks if the number is positive.
  • The condition number == 0 checks if the number is zero.
  • The condition number < 0 checks if the number is negative.

The above program can also be written using the nested if...else statement.

Example 2: Check Number Type with nested if...else

// check if the number is positive, negative or zero
const number = prompt("Enter a number: ");

if (number >= 0) {
    if (number == 0) {
        console.log("The number is zero");
    } else {
        console.log("The number is positive");
    }
} else {
    console.log("The number is negative");
}

Output

Enter a number: 0
You entered number zero

The above program works the same as Example 1. However, the second example uses the nested if...else statement.


Also Read:

Before we wrap up, let’s put your knowledge of Javascript Program to Check if a number is Positive, Negative, or Zero to the test! Can you solve the following challenge?

Challenge:

Write a function to check if a number is negative.

  • If the given number num is less than 0, return "Negative". Otherwise, return "Not Negative".
  • For example, if num = -4, the expected output is "Negative".
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges