Value Is Plain Object

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the concept of checking whether a given value is a plain object or not using JavaScript. We will use the isPlainObject() function to check if the provided value is an object created by the Object constructor. By the end of this lab, you will have a better understanding of how to determine if an object is plain or not in JavaScript.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced 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/obj_manip("`Object Manipulation`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28434{{"`Value Is Plain Object`"}} javascript/data_types -.-> lab-28434{{"`Value Is Plain Object`"}} javascript/arith_ops -.-> lab-28434{{"`Value Is Plain Object`"}} javascript/comp_ops -.-> lab-28434{{"`Value Is Plain Object`"}} javascript/obj_manip -.-> lab-28434{{"`Value Is Plain Object`"}} javascript/destr_assign -.-> lab-28434{{"`Value Is Plain Object`"}} end

Check if a Value is a Plain Object

To check if a value is a plain object, follow these steps:

  • Check if the value is truthy.
  • Use typeof to check if it is an object.
  • Use Object.prototype.constructor to make sure the constructor is equal to Object.

Use the following code to implement this check:

const isPlainObject = (val) =>
  !!val && typeof val === "object" && val.constructor === Object;

You can test this function with the following examples:

isPlainObject({ a: 1 }); // true
isPlainObject(new Map()); // false

To start practicing coding, open the Terminal/SSH and type node.

Summary

Congratulations! You have completed the Value Is Plain Object lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like