JS Example for Beginners: Javascript Program to Check if a number is Positive, Negative, or Zero

(JavaScript programming Example for Beginners)

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

In this example, you will learn to check whether the number entered by the user is positive, negative or zero.

 


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
let 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
let 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.

 

 

JS Example for Beginners: Javascript Program to Check if a number is Positive, Negative, or Zero

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.