Type of Value

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the concept of data types in JavaScript. We will learn how to use the getType function to determine the native type of any given value, whether it is undefined, null, or an instance of a constructor. By the end of the lab, you will have a solid understanding of how to work with different data types in JavaScript.


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`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") subgraph Lab Skills javascript/variables -.-> lab-28673{{"`Type of Value`"}} javascript/data_types -.-> lab-28673{{"`Type of Value`"}} javascript/arith_ops -.-> lab-28673{{"`Type of Value`"}} javascript/comp_ops -.-> lab-28673{{"`Type of Value`"}} javascript/cond_stmts -.-> lab-28673{{"`Type of Value`"}} end

Function to Get Type of Value

To get the type of a value, use the following function:

const getType = (v) => {
  if (v === undefined) {
    return "undefined";
  }

  if (v === null) {
    return "null";
  }

  return v.constructor.name;
};
  • The function returns 'undefined' or 'null' if the value is undefined or null.
  • Otherwise, it returns the name of the constructor by using Object.prototype.constructor and Function.prototype.name.

Example usage:

getType(new Set([1, 2, 3])); // 'Set'

Summary

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

Other JavaScript Tutorials you may like