Clamping Numbers in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the concept of clamping a number within a specified range in JavaScript. The purpose of this lab is to help you understand how to limit the value of a number to a certain range, which is a common programming task in various applications. By the end of this lab, you will have a clear understanding of how to implement the clampNumber function in your JavaScript code.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28196{{"`Clamping Numbers in JavaScript`"}} javascript/data_types -.-> lab-28196{{"`Clamping Numbers in JavaScript`"}} javascript/arith_ops -.-> lab-28196{{"`Clamping Numbers in JavaScript`"}} javascript/comp_ops -.-> lab-28196{{"`Clamping Numbers in JavaScript`"}} end

Function to Clamp a Number within a Range

To clamp a number within a specified range, use the clampNumber function.

To start, open the Terminal/SSH and type node to practice coding.

The clampNumber function takes in three parameters: num, a, and b. It clamps num within the inclusive range specified by the boundary values a and b and returns the result.

If num falls within the range, the function returns num. Otherwise, it returns the nearest number in the range.

Here's the code for the clampNumber function:

const clampNumber = (num, a, b) =>
  Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));

And here are some examples of how to use the function:

clampNumber(2, 3, 5); // 3
clampNumber(1, -1, -5); // -1

Summary

Congratulations! You have completed the Clamp Number lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like