JavaScript Type Checking | Programming Tutorials

Labby - Aug 30 - - Dev Community

Introduction

This article covers the following tech skills:

Skills Graph

In this lab, we will explore a JavaScript function that checks whether a provided value is of a specified type. We will use the is() function, which leverages the constructor property and Array.prototype.includes() method to determine if the value is of the specified type. This lab will help you gain a better understanding of type checking in JavaScript.

Function to Check if Value Is of Type

To check if a provided value is of a specified type, follow these steps:

  • Ensure that the value is not undefined or null by using Array.prototype.includes().
  • Use Object.prototype.constructor to compare the constructor property on the value with the specified type.
  • The function is() below performs these checks and returns true if the value is of the specified type, and false otherwise.
const is = (type, val) => ![, null].includes(val) && val.constructor === type;
Enter fullscreen mode Exit fullscreen mode

You can use is() to check if a value is of various types, such as Array, ArrayBuffer, Map, RegExp, Set, WeakMap, WeakSet, String, Number, and Boolean. For example:

is(Array, [1]); // true
is(Map, new Map()); // true
is(String, ""); // true
is(Number, 1); // true
is(Boolean, true); // true
Enter fullscreen mode Exit fullscreen mode

Summary

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

MindMap


🚀 Practice Now: Check if Value Is of Type


Want to Learn More?

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player