Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 904
Hemadri Dasari Avatar asked Sep 22 '18 04:09

Hemadri Dasari


People also ask

What is a plain JavaScript object?

The plain object is, in other words, an Object object. It is designated "plain" in jQuery documentation to distinguish it from other kinds of JavaScript objects: for example, null, user-defined arrays, and host objects such as document, all of which have a typeof value of "object."

What is the difference between object and object in JavaScript?

Javascript is case sensitive "object" is essentially a variable that can hold anything. "Object" is an actual javascript type.

What is the difference between object and method in JavaScript?

A method is a block of code that can be called by name within the program. An Object is an instance of a class. They may contain methods or attributes that define what they are. Not similar at all.


2 Answers

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");
like image 122
Mamun Avatar answered Sep 30 '22 02:09

Mamun


Plain object(POJO - Plain Old Javascript Object)

var plainObj1 = {}; // typeof plainObj1 --> Object
var plainObj2 = {name : "myName"}; // typeof plainObj2 --> Object
var plainObj3 = new Object(); // typeof plainObj3 --> Object

Non Plain object

var Person = function(){}; //class
var nonPlainObj = new Person(); // typeof nonPlainObj --> function
like image 24
Sathish Avatar answered Sep 30 '22 01:09

Sathish