DEV Community

Cover image for Explore JavaScript Data Types with getType Function
Labby for LabEx

Posted on

3

Explore JavaScript Data Types with getType Function

Introduction

This article covers the following tech skills:

Skills Graph

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.

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;
};
Enter fullscreen mode Exit fullscreen mode
  • 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'
Enter fullscreen mode Exit fullscreen mode

Summary

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

MindMap


πŸš€ Practice Now: Type of Value


Want to Learn More?

Top comments (2)

Collapse
 
kooiinc profile image
KooiInc β€’

But wait: getType(+("NaN")) => Number? getType(1/0) => Number?

This small module may be more useful.

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ β€’

You've missed BigInt from the primitive types

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay