YogeshChauhan . com

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

amazon

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 uninstall Cocoapods from the Mac OS? #4 How to add Read More Read Less Button using JavaScript? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

May 7 How to disable right click and drag and drop of images using jQuery? May 7 How to render Lists in React? May 7 What’s the difference between variables in CSS and SCSS (Sass)? May 7 How to define variables in SCSS (Sass)? May 7 How to show and hide an element on click in React? May 5 Use inline if to make a shorter conditional syntax in React

You might also like these

How to Check If a Variable is an Integer, a Float, a Number, NaN, an Infinite or a Numeric in PHP?PHPAlways add associated labels to your Form elementsUI/UXHow to auto-resize textarea based on text input using JavaScript or jQuery?JavaScriptWhat does JSX do in React?ReactHow to create a flip pricing table using CSS and JavaScript?CSSColumn and Table Alias in PostgresPostgres