How to use switch case In Javascript
In this method we are using switch case for solving this problem. Switch statement will check the condition and return the result. If any of case is equivalent to that result then that code block will get executed and it will print result in the console else default statement will get executed automatically.
Example: It describes how we can find the given number is Positive, Negative, or Zero using switch case
// JavaScript program for checking if number
// is positive, negative or zero
let num = 10;
// Switch-case statement
switch (num / num) {
case 1:
console.log("Positive nunber");
break;
case -1:
console.log("Negative number");
break;
case 0:
console.log("Zero");
break;
}
Output
Positive nunber
Time complexity: O(1), as it is doing constant operations
Space complexity: O(1), as it is using constant space for variables
JavaScript Program to Check if a Given Integer is Positive, Negative, or Zero
In this article, we will discuss how we can determine whether the given number is Positive, Negative, or Zero. As we know if the number is less than 0 then it will be called a “Negative” number if it is greater than 0 then it will be called a “Positive” number. And if it doesn’t lie between them, then it will be 0.
Example:
Input: 10
Output: Positive number
Input: -12
Output: Negative number
Input: 0
Output: Zero
These are the following ways by which we can find out whether the number is Positive, Negative, or Zero:
Table of Content
- Using if-else statement
- Using ternary operator
- Using switch case
- Using Math.sign()
- Using bitwise operators