Check if a Number is Between Two Numbers in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

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 used the && (and) operator to check if two 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.

The logical AND (&&) operator returns the value to the left if it's falsy, otherwise it returns the value to the right.

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

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

index.js
console.log('' && 'hi'); // 👉️ ''

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.

Use the search field on my Home Page to filter through my more than 3,000 articles.