Kodeclik Blog

How to check if a number is between two numbers in JavaScript

Consider a simple Javascript program that has a month number in a variable and you desire to determine whether it is Winter (months 12,1,and 2), Spring (months 3-5), Summer (6-8), or Fall (9-11).
Let us first focus on determining if it is Spring. We write one condition to check if the value is greater than or equal to 3. We write a second condition to check if the value is less than or equal to 5. Finally we combine them with an and (&&) operator.
We will embed our Javascript code inside a HTML page like so:
In the above HTML page you see the basic elements of the page like the head element containing the title (“Javascript code example”) and a body with an empty script tag. The Javascript code goes inside these tags.
Here is some basic code to check if a given month falls within the Spring bracket:
The output will be:
If you change the month variable to 8, for instance, you will get:
Let us expand the code to cover the other seasons. Summer and Fall are similar in format to the above code blocks. We use the “else” condition to trap for Winter because it involves a non-contiguous set of months.
An advantage of the above way of checking if a value is in between a given range is that the && operator “short circuits”, i.e., if the first condition is not met then the second condition is not evaluated because there is no way for the overall AND expression to be true if one of them evaluates to false.
Interested in more Javascript tidbits? Checkout our blog post on Javascript exponentiation operators.
Want to learn Javascript with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2024. All rights reserved.