Check if a Number is Between Two Numbers in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 15 20212 min read

Check if a Number is Between Two Numbers #

To check if a number is between two numbers:

  1. Use the && (and) operator to chain two conditions.
  2. In the first condition check that the number is greater than the lower range and in the second, that the number is lower than the higher range.
  3. If both conditions are met, the number is in the range.
index.js
const num = 50; const low = 30; const high = 150; if (num > low && num < high) { console.log('โœ… num is between values'); } else { console.log('โ›”๏ธ num is NOT between values'); }

We use the && (and) operator to check if both conditions are true.

The if block only runs if these two conditions are met:

  • the number is greater than the lower value
  • the number is lower than the higher value

If both conditions are met, we know that the number is in the specified range, otherwise it isn't.

The && operator is evaluated left to right. If the first condition in our if statement returns false, the operator short-circuits and doesn't evaluate the second condition.

For example, in the following if statement, the 5 > 1 condition is never evaluated.

index.js
if (1 > 100 && 5 > 1) { }

We first check if 1 > 100 and get a value of false, so the && operator short-circuits.

Here are some more examples of using the && (and) operator.

index.js
console.log(true && true); // ๐Ÿ‘‰๏ธ true console.log(true && false); // ๐Ÿ‘‰๏ธ false console.log(false && true); // ๐Ÿ‘‰๏ธ false console.log('test' && 'hi'); // ๐Ÿ‘‰๏ธ 'hi' console.log('test' && ''); // ๐Ÿ‘‰๏ธ '' console.log('' && 'hi'); // ๐Ÿ‘‰๏ธ ''

The && operator returns the value of one of the operands.

If the first value we pass to it is a falsy value, it returns the first value, otherwise it returns the second.

Falsy values in JavaScript are: undefined, null, NaN, empty string, false and 0.

In our last example, because we used an empty string as the first value and an empty string is falsy, it got returned from the && operator.

In short, if the value to the left is falsy, it gets returned from the && operator. In all other cases the operator returns the value to the right.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee