How to Check the Type of a Variable or Object in JavaScript

How to Check the Type of a Variable or Object in JavaScript

JavaScript has a special operator called typeof which lets you get the type of any value. We will learn how typeof is used. The type of a variable is determined by the type of the value assigned to it. JavaScript Data Types, in JavaScript, there are seven primitive types: String, Number, BigInt, Symbol, Boolean, undefined, null

Data types and type checking are fundamental aspects of any programming language.

Many programming languages like Java have strict type checking. This means that if a variable is defined with a specific type it can contain a value of only that type.

JavaScript, however, is a loosely typed (or dynamically typed) language. This means that a variable can contain a value of any type. JavaScript code can execute like this:

let one = 1;
one = 'one';
one = true;
one = Boolean(true);
one = String('It is possible');

With this in mind, it is critical to know the type of a variable at any given time.

The type of a variable is determined by the type of the value assigned to it. JavaScript has a special operator called typeof which lets you get the type of any value.

In this article, we will learn how typeof is used, along with a few gotchas to watch out for.

JavaScript Data Types

Let's take a quick look at JavaScript data types before we dig into the typeof operator.

In JavaScript, there are seven primitive types. A primitive is data that is not an object and has no methods. They are:

  1. String
  2. Number
  3. BigInt
  4. Symbol
  5. Boolean
  6. undefined
  7. null

Everything else is an object – even including array and function. An object type is a collection of key-value pairs.

The typeof Operator

The typeof operator takes only one operand (a unary operator) and evaluates its type to return the type as a string. Here is how you use it when you're evaluating the type of a number, 007.

typeof 007;  // returns 'number'

There is alternative syntax for the typeof operator where you can use it like a function:

typeof(operand)

This syntax is useful when you want to evaluate an expression rather than a single value. Here is an example of that:

typeof(typeof 007); // returns 'string'

In the above example, the expression typeof 007 evaluates to the type number and returns the string 'number'. typeof('number') then results in 'string'.

Let's look at another example to understand the importance of the parenthesis with the typeof operator.

typeof(999-3223); // returns, "number"

If you omit the parenthesis, it will return, NaN(Not a Number):

typeof 999-3223; // returns, NaN

This is because, first typeof 999 will result in a string, "number". The expression "number" - 32223 results in NaN as happens when you perform a subtraction operation between a string and number.

Examples

The following code shows the type check of various values using the typeof operator.

typeof 0;  //'number'
typeof +0;  //'number'
typeof -0;  //'number'
typeof Math.sqrt(2);  //'number'
typeof Infinity;  //'number'
typeof NaN;  //'number', even if it is Not a Number
typeof Number('100');  //'number', After successfully coerced to number
typeof Number('freeCodeCamp');  //'number', despite it can not be coerced to a number

typeof true;  //'boolean'
typeof false;  //'boolean'
typeof Boolean(0);  //'boolean'

typeof 12n;  //'bigint'

typeof '';  //'string'
typeof 'freeCodeCamp';  //'string'
typeof `freeCodeCamp is awesome`;  //'string'
typeof '100';  //'string'
typeof String(100); //'string'

typeof Symbol();  //'symbol'
typeof Symbol('freeCodeCamp');  //'symbol'

typeof {blog: 'freeCodeCamp', author: 'Tapas A'};  //'object';
typeof ['This', 'is', 101]; //'object'
typeof new Date();  //'object'
typeof Array(4);  //'object'

typeof new Boolean(true);  //'object'; 
typeof new Number(101);  //'object'; 
typeof new String('freeCodeCamp');  //'object';
typeof new Object;  //'object'

typeof alert;  //'function'
typeof function () {}; //'function'
typeof (() => {});  //'function' - an arrow function so, parenthesis is required
typeof Math.sqrt;  //'function'

let a;
typeof a;  //'undefined'
typeof b;  //'undefined'
typeof undefined;  //'undefined'

typeof null;  //'object'

The table below summarizes the possible return values of typeof:

Common Gotchas with typeof

There are cases where the typeof operator may not return types you'd expect. This may cause confusion and errors. Here are a few cases.

The type of NaN is a number

typeof NaN;  //'number', even if it is Not a Number

The typeof NaN is 'number'. This is strange, as we shouldn't be detecting a NaN using typeof. There are better ways to deal with it. We will see them in a minute.

The type of null is the object

  typeof null;  //'object'

In JavaScript, typeof null is an object which wrongly suggests that null is an object where it is a primitive value.

This is actually a bug in the language and an attempt was made to fix it. But it was rejected because of backward compatibility issues.

The type of an undeclared variable is undefined

Before ES6, a type check on an undeclared variable used to result in 'undefined'. But this is not an error-safe way to deal with it.

With ES6 we have block-scoped variables declared using the let or const keywords. These will throw a ReferenceError when used with the typeof operator before they are initialized.

 typeof cat; // ReferenceError
 let cat = 'brownie'; 

The type of a constructor function is an object

All constructor functions, except for the Function constructor, will always be typeof 'object'.

typeof new String('freeCodeCamp'); //'object'

This may lead to some confusion, as we expect it to be the actual type (in the above example, a string type).

The type of an Array is an object

Though technically correct, this could be the most disappointing one. We want to differentiate between an Array and Object even if an Array is technically an Object in JavaScript.

typeof Array(4);  //'object'

Fortunately there are ways to detect an Array correctly. We will see that soon.

Beyond typeof – Better Type Checking

Now that we've seen some of the limitations with the typeof operator, let's see how to fix them and do better type checking.

How to Detect NaN

In JavaScript, NaN is a special value. The value NaN represents an outcome when the result of an arithmetic expression can not be represented. For example,

let result = 0/0;
console.log(result);  // returns, NaN

Also, if we perform any arithmetic operations that involve NaN, it will always result in a NaN.

console.log(NaN + 3); // returns, NaN

The type checking on NaN using the typeof operator doesn't help much as it returns the type as a 'number'. JavaScript has a global function called isNaN() to detect if a result is NaN.

isNaN(0/0); // returns, true

But there is a problem here, too.

isNaN(undefined); // returns true for 'undefined'

In ES6, the method isNaN() is added to the global Number object. This method is much more reliable and so it's the preferred one.

Number.isNaN(0/0); // returns, true
Number.isNaN(undefined); // returns, false

Another interesting aspect of NaN is that it is the only JavaScript value that is never equal to any other values including itself. So this is another way to detect NaN for the environments where ES6 is not supported:

function isNaN (input) {
  return input !== input;
}

How to Detect null

As we have seen, detecting null using the typeof operator is not useful. The preferred way to check if something is null is by using the strict equality operator(===).

function isNull(input) {
 return input === null;
}

Make sure not to use the == by mistake. Using the == in place of === will result in misleading type detection.

How to Detect an Array

From ES6 onwards, we can detect an array using the Array.isArray method.

Array.isArray([]); // returns true
Array.isArray({}); // returns false

Prior to ES6, we could use the instanceof operator to determine an Array:

function isArray(input) {
  return input instanceof Array;
}

A Generic Solution to Type Checking

There is a way we can create a generic solution to type checking. Have a look at the method, Object.prototype.toString. This is very powerful and extremely useful for writing a utility method for type checking.

When Object.prototype.toString is invoked on a value using call() or apply(), it returns the object type in the format: [object Type]. The Type in the return value is the actual type.

Let's see how it works with some examples:

// returns '[object Array]'
Object.prototype.toString.call([]); 

// returns '[object Date]'
Object.prototype.toString.call(new Date()); 

// returns '[object String]'
Object.prototype.toString.call(new String('freeCodeCamp'));

// returns '[object Boolean]'
Object.prototype.toString.call(new Boolean(true));

// returns '[object Null]'
Object.prototype.toString.call(null);

So this means that if we just take the return string and take out the Type part, we will have the actual type. Here is an attempt to do this:

function typeCheck(value) {
  const return_value = Object.prototype.toString.call(value);
  // we can also use regex to do this...
  const type = return_value.substring(
           return_value.indexOf(" ") + 1, 
           return_value.indexOf("]"));

  return type.toLowerCase();
}

Now, we can use the typeCheck function to detect the types:

typeCheck([]); // 'array'
typeCheck(new Date()); // 'date'
typeCheck(new String('freeCodeCamp')); // 'string'
typeCheck(new Boolean(true)); // 'boolean'
typeCheck(null); // 'null'

In Summary

To Summarize what we've learned in this article:

  • JavaScript type checking is not as strict as other programming languages.
  • Use the typeof operator for detecting types.
  • There are two variants of the typeof operator syntax: typeof and typeof(expression).
  • The result of a typeof operator may be misleading at times. We need to rely on other available methods (Number.isNaN, Array.isArry, and so on) in those cases.
  • We can use Object.prototype.toString to create a generic type detection method.

Before we end...

Thank you for reading this far! Let's connect. You can @ me on Twitter (@tapasadhikary) with comments.

The Original Article can be found on freecodecamp.org

javascript web-development programming developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

What Garbage Collection in JavaScript Is and How It Works

JavaScript values are allocated when things are created (objects, Strings, etc.) and freed automatically when they are no longer used. This process is called Garbage collection.

What Javascript Spread Operator is, How It Works and How to Use It

JavaScript spread operator is one of the more popular features that were introduced in ES6. This tutorial will help you understand it. You will learn what spread operator is and how it works. You will also learn how to use it to copy and merge arrays and object literals, insert data and more.

Top 10 Web Development Trends in 2020 | Web Development Skills

Top 10 Web Development Trends in 2020 will provide you with a detailed list of the trends which are currently being noticed. Upskilling to these trends will help you in landing onto better jobs in 2020-2021.