YogeshChauhan.com
4 different ways to create JavaScript Objects
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

dreamhost

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 3 How to embed YouTube or other video links in WordPress? Mar 3 How to change the Login Logo in WordPress? Mar 3 substring() Method in JavaScript Mar 3 Window setInterval() Method in JavaScript Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS

You might also like these

How to animate list items using CSS and JavaScript?CSSSafe Practice to add Links to cross-origin destinationUI/UXHow to add Read More Read Less Button using JavaScript?JavaScriptCROSS JOIN in PostgresPostgresThe simple difference between var, let and const in JavascriptJavaScriptHow to Make a Simple Module with a Form and Menu Link in Drupal 7.x?Drupal