DEV Community

Avnish
Avnish

Posted on

Check if Number is not Greater than 0 in JavaScript

Here's a JavaScript code snippet to check if a number is not greater than 0, along with 5 examples, explanations, and their outputs:

// Function to check if a number is not greater than 0
function isNotGreaterThanZero(number) {
    // Checking if the number is not greater than 0
    return !(number > 0);
}

// Example 1: Number is not greater than 0
const example1 = 0;
console.log("Example 1:", example1, "is not greater than 0:", isNotGreaterThanZero(example1)); // Output: true

// Example 2: Number is greater than 0
const example2 = 5;
console.log("Example 2:", example2, "is not greater than 0:", isNotGreaterThanZero(example2)); // Output: false

// Example 3: Number is negative
const example3 = -3;
console.log("Example 3:", example3, "is not greater than 0:", isNotGreaterThanZero(example3)); // Output: true

// Example 4: Number is a floating point
const example4 = 0.001;
console.log("Example 4:", example4, "is not greater than 0:", isNotGreaterThanZero(example4)); // Output: false

// Example 5: Number is NaN (Not a Number)
const example5 = NaN;
console.log("Example 5:", example5, "is not greater than 0:", isNotGreaterThanZero(example5)); // Output: true
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. The function isNotGreaterThanZero takes one parameter: number (the number to be checked).
  2. Inside the function, it uses a comparison number > 0 to check if the number is greater than 0.
  3. The ! operator is used to negate the result of the comparison, effectively checking if the number is not greater than 0.
  4. If the number is not greater than 0, the function returns true, indicating that the condition is met. Otherwise, it returns false.
  5. Examples demonstrate different scenarios including numbers equal to 0, positive numbers, negative numbers, floating-point numbers, and NaN (Not a Number).
  6. Outputs show whether each example number is not greater than 0 (true) or not (false).

Top comments (0)