Introduction
In this lab, we will explore the concept of checking whether a given number falls within a specified range. We will use arithmetic comparison to check if the number is in the range and handle cases where the end of the range is not specified. By the end of the lab, you will have a better understanding of how to check if a number is within a given range in JavaScript.
Function to Check if a Number is Within a Given Range
To check if a number falls within a specified range, use the inRange function. Begin by opening the Terminal/SSH and typing node to start coding.
Here are the steps to use the inRange function:
- Use arithmetic comparison to check if the given number is in the specified range.
- If the second argument,
end, is not specified, the range is considered to be from0tostart. - The
inRangefunction takes three arguments:n,start, andend. - If
endis less thanstart, the function swaps the values ofstartandend. - If
endis not specified, the function checks ifnis greater than or equal to 0 and less thanstart. - If
endis specified, the function checks ifnis greater than or equal tostartand less thanend. - The function returns
trueifnis within the specified range, andfalseotherwise.
Here is the inRange function:
const inRange = (n, start, end = null) => {
if (end && start > end) [end, start] = [start, end];
return end == null ? n >= 0 && n < start : n >= start && n < end;
};
Here are some examples of how to use the inRange function:
inRange(3, 2, 5); // true
inRange(3, 4); // true
inRange(2, 3, 5); // false
inRange(3, 2); // false
Summary
Congratulations! You have completed the Number in Range lab. You can practice more labs in LabEx to improve your skills.