Yogesh Chauhan's Blog

4 different ways to create JavaScript Objects

in JavaScript on January 3, 2021

Objects in JavaScript are same as objects in real life. In other words, the concept of objects in JavaScript can be understood with real life, tangible objects.

In JavaScript, an object is a standalone entity, with properties and type. Compare it with a car, for example. A car is an object, with properties. A car has a color, a design, weight, a material it is made of, etc. The same way, JavaScript objects can have properties, which define their characteristics.

Objects are like Variables. JavaScript variables can contain single values.

For example,


var person = "John Doe"; 

But objects can contain many values.

For example,


var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Creating Objects

There are different ways to create JavaScript objects. Let’s go through one by one each.

1. Using the JavaScript Keyword new

For example,


var person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
console.log(person.firstName);

//output 
John

The example above creates a new JavaScript object with four properties.

We can create objects using the keyword new and then assign properties and values using objectName.propertyName (dot notation).

2. Using an Object Literal

For example,


var person = {firstName:"John", lastName:"Doe", age:50, 
                    eyeColor:"blue"};
console.log(person.firstName);

//output 
John

The example above creates a new JavaScript object with four properties as well just like the previous example.

This is the easiest way to create a JavaScript Object because using an object literal, you both define and create an object in one statement.

An object literal is a list of name:value pairs (like age:50) inside curly braces {}.

3. Create JavaScript Object with Constructor

For example,


function Vehicle(name, maker) {
        this.name = name;
        this.maker = maker;
}

let car1 = new Vehicle('Fiesta', 'Ford');
let car2 = new Vehicle('Santa Fe', 'Hyundai')
console.log(car1.name);    //Output: Fiesta
console.log(car2.name);    //Output: Santa Fe

Constructor is nothing but a function.

To define an object type, create a function for the object type that specifies its name, properties, and methods. Just like we did in the example above with Vehicle object.

With help of new keyword, constructor function allows to create multiple objects of same flavor as shown below

Every function, while executing has a reference to its current execution context called this (it’s a keyword). The use of this to assign values to the object’s properties based on the values passed to the function.

The new keyword in front of any function turns the function call into constructor call.

4. Create JavaScript Object using classes

For example,


class Vehicle {
  constructor(name, maker, engine) {
  this.name = name;
  this.maker =  maker;
  this.engine = engine;
 }
}

let bike1 = new Vehicle('Hayabusa', 'Suzuki', '1340cc');
let bike2 = new Vehicle('Ninja', 'Kawasaki', '998cc');
console.log(bike1.name);    //Output: Hayabusa
console.log(bike2.maker);   //Output: Kawasaki

With the new ECMAScript 6 (newer version of javascript), it supports class concept like any other Statically typed or object oriented language. So, object can be created out of a class in javascript as shown in the example above.

Methods can be part of class while declaration can be added later to the created object as shown below.   


class Vehicle {
  constructor(name, maker, engine) {
  this.name = name;
  this.maker =  maker;
  this.engine = engine;
}
  start() {
    console.log(Starting...);
  }
}
let bike = new Vehicle('Hayabusa', 'Suzuki', '1340cc');
bike.start();    

//Output: Starting...

/* Adding method brake() later to the created object */

bike.brake = function() {
  console.log(Applying Brake...);
}

bike.brake();    

//Output: Applying Brake...

Summary

We learnt about the new keyword and how to create objects with it and then we went through Object literal, the most common way to create JavaScript object, then understood the constructor function which helps to create multiple objects of same flavor and finally new way of creating JavaScript object with classes.

Sources


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to animate list items using CSS and JavaScript?CSSHow to uninstall Cocoapods from the Mac OS?MiscellaneousHow to catch .keypress() on body using jQuery?jQueryHTML canvas methodsHTMLCanvas Drawing in HTML5HTMLWP_Query Class in WordPressWordPress