Value Is Number

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will focus on creating a JavaScript function that checks whether a given value is a number. We will make use of the typeof operator and a safeguard against NaN to ensure that the function returns true only for valid numbers. This lab will help you improve your understanding of JavaScript data types and type checking.


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-28430{{"`Value Is Number`"}} javascript/data_types -.-> lab-28430{{"`Value Is Number`"}} javascript/arith_ops -.-> lab-28430{{"`Value Is Number`"}} javascript/comp_ops -.-> lab-28430{{"`Value Is Number`"}} end

Checking if a Value is a Number in JavaScript

To check if a value is a number in JavaScript, you can use the typeof operator to determine if the value is classified as a number primitive. To prevent issues with NaN, which has a typeof equal to number and is not equal to itself, you can also check if the value is equal to itself using val === val.

Here's an example function that checks if a given value is a number:

const isNumber = (val) => typeof val === "number" && val === val;

You can use this function like so:

isNumber(1); // true
isNumber("1"); // false
isNumber(NaN); // false

Summary

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

Other JavaScript Tutorials you may like