DEV Community

Cover image for Javascript plain object!
Hosein Pouyanmehr
Hosein Pouyanmehr

Posted on • Originally published at hpouyanmehr.com

Javascript plain object!

You can read about code-pool concepts on this link.

This post was first published on my blog. You can read it at this link for a focused and better reading experience.

About this post

In this post, we’ll create a utility to ensure a given value is an actual object—not null or an array. This will prevent unexpected behavior.

Table of Contents


What is a plain object in JavaScript?

JS is somewhat weird in its nature. As you may know, not only objects but also null and arrays have the type object. If you don’t believe me, try running the following code:

console.log(typeof null);

console.log(typeof []);
Enter fullscreen mode Exit fullscreen mode

This behavior can lead to unpredictable issues. For example, when you create a function to merge two objects, if you don’t ensure the inputs are actually objects, you may encounter errors or unexpected results. The following function helps you verify that your input is a real object.


Utility: isPlainObject()

Here it is, simple and straightforward.

export const isPlainObject = (value: unknown): value is Record<string, unknown> => 
  typeof value === 'object' && value !== null && !Array.isArray(value);
Enter fullscreen mode Exit fullscreen mode

You can find the code and useful JSDoc at this GitHub link.

Top comments (0)