Search code examples
javascriptjavascript-objects

The difference between object and plain object in JavaScript?


Couldn’t understand the difference between object and plain object in JavaScript.

I know how Object looks like but don’t understand plain object. I googled about this but couldn’t understand.

As per my understanding normal object looks like below

const object = {};

Or we do call functions as objects in JavaScript

function test() {

}

But what is plain object? how it differs with normal object. Thank you

Edit:

My confusion started about plain object after looking at below error. So my query is to understand the concept of plain object in JavaScript

Actions must be plain objects. Use custom middleware for async actions.


Solution

  • I think you wanted to mean Plain Old JavaScript Object as plain object.

    In vanilla JavaScript a POJO (Plain Old JavaScript Object) is the simplest kind of object you could possibly have: a set of key-value pairs, created by the {} object literal notation or constructed with new Object().

    Plain Old JavaScript Object:

    Using the bracket's syntactic sugar also known as object literal:

    var obj = {};
    

    Using the Object() constructor:

    var obj = new Object();
    

    Other Than Plain Object:

    Using a function constructor:

    var Obj = function(name) {
      this.name = name;
    }
    var c = new Obj("hello"); 
    

    Using ES6 class syntax:

    class myObject  {
      constructor(name) {
        this.name = name;
      }
    }
    var e = new myObject("hello");