paint-brush
Three Different Ways to Create Objects in JavaScriptby@ashutosh-kumar-singh
552 reads
552 reads

Three Different Ways to Create Objects in JavaScript

by ASHUTOSH KUMAR SINGHJune 7th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

JavaScript is an object, whether it’s an array or a function. In this post, we’ll learn three different ways to create objects in JavaScript. Object literals encapsulate data, enclosing it in a tidy package. With the built-in Object Constructor in Javascript,creates an empty object; or, this keyword can be used with a user-defined constructor function. The next step is to add properties and methods to this empty object. If you use the same name for two properties, the second property will overwrite the first.

Company Mentioned

Mention Thumbnail
featured image - Three Different Ways to Create Objects in JavaScript
ASHUTOSH KUMAR SINGH HackerNoon profile picture

Almost everything in Javascript is an object, whether it’s an array or a function. In this post, we’ll learn three different ways to create objects in JavaScript:

  1. Object Literals
  2. New Keyword
  3. Class

Object Literals

A JavaScript object literal is a comma-separated list of name-value pairs wrapped in curly braces. Object literals encapsulate data, enclosing it in a tidy package.

let Person = {
  name: "Foziya",
  age: 20,
  action: ["walk", " run"],
  greeting: function() {
    console.log("Hello");
  }
};

Object literal property values can be of any data type, including array literals, function literals, and nested object literals.

let shape = {
  name: "rectangle",
  color: "red",
  size: {
    length: 10,
    breadth: 20
  }
};

console.log(shape);
 // { name: 'rectangle',
 // color: 'red',
 // size: { length: 10, breadth: 20 } }
 
console.log(shape.size.length)
// 10

Shorthand property names

Consider a scenario in which you have to put different variables inside an object. One way of doing it is:

let one = 1;
let two = 2;
let three = 3;

let numbers = {
  one: one,
  two: two,
  three: three
};
console.log(numbers);

//{ one: 1, two: 2, three: 3 }

With ECMAScript 2015, a shorter notation is available to achieve the same thing:

let one = 1;
let two = 2;
let three = 3;

let numbers = { one, two, three };

console.log(numbers);
//{ one: 1, two: 2, three: 3 }

console.log(numbers.one)
// 1

console.log(numbers.one === { one }.one);
// true 

Duplicated property names

If you use the same name for two properties, the second property will overwrite the first.

let Person = {
  name: "Ney Vatsa",
  name: "Shashank"
};
console.log(Person.name);

// Shashank

New
 Keyword

The 

Object
 constructor creates an object wrapper for a given value. If the value is
null
or 
undefined
, it will create and return an empty object. Otherwise, it will return an object of a type that corresponds to the given value.

Objects can also be created using the 

new
keyword. With the built-in Object Constructor in Javascript, 
new
creates an empty object; or, this keyword can be used with a user-defined constructor function:
with builtin Object Constructor
.

To get started, first take a look at this example:


let movies = new Object();

console.log(movies)
//{}

The next step is to add properties and methods to this empty object. This can be achieved with simple dot notation:

let movies = new Object();

console.log(movies)
//{}

movies.name = "Dead Poets Society";
movies.releaseYear = 1989;
movies.genre = ["Drama", "Teen"];
movies.ratings = {
  IMDb: "8.1 / 10",
  Metacritic: "79%"
};
movies.watch = () => {
  console.log("Watch Online");
};

console.log(movies);
// { name: 'Dead Poets Society',
//  releaseYear: 1989,
//  genre: [ 'Drama', 'Teen' ],
//  ratings: { IMDb: '8.1 / 10', Metacritic: '79%' },
//  watch: [Function] }

movies.watch();
// Watch Online

However, this practice is not recommended, as there is a scope resolution behind the scenes to check if the constructor function is built-in or user-defined.

User-defined constructor functions

Functions can also be used to create objects in JavaScript. If you really think about it, they’re already objects — so basically, objects are used to create more objects.

Generally, this method is preferred over the object constructor. Imagine you have to create hundreds of objects with the same properties; with the object constructor method you’ll have to manually add all the properties to all the objects but with function constructor, these properties can be predefined.

function movies(name, releaseYear, genre, ratings) {
  this.name = name;
  this.releaseYear = releaseYear;
  this.genre = genre;
  this.ratings = ratings;
  this.watch = () => {
    console.log("Watch Online");
  };
}

let DPS = new movies("Dead Poets Society", 1989, ["Drama", "Teen"], {
  IMDb: "8.1 / 10",
  Metacritic: "79%"
});

console.log(DPS);movies {
//     name: 'Dead Poets Society',
//         releaseYear: 1989,
//             genre: ['Drama', 'Teen'],
//                 ratings: { IMDb: '8.1 / 10', Metacritic: '79%' },
//     watch: [Function]
// }


let rocky = new movies("Rocky", 1976, ["Drama", "Sports"], {
  IMDb: "8.1 / 10",
  Metacritic: "70%"
});

console.log(rocky);

// movies {
//     name: 'Rocky',
//         releaseYear: 1976,
//             genre: ['Drama', 'Sports'],
//                 ratings: { IMDb: '8.1 / 10', Metacritic: '70%' },
//     watch: [Function]
// }

Using the same function constructor, any number of objects can be created.

Using ES6 Classes to Create Objects

This method is a lot similar to using new with the user-defined function constructor. Classes are the primary components of Object Oriented Programming (OOP). Many instances of classes can be created which are in fact objects. The constructor functions can now be replaced by classes, as they are supported in ES6 specifications.

class Movies {
  constructor(name, releaseYear, genre, ratings) {
    this.name = name;
    this.releaseYear = releaseYear;
    this.genre = genre;
    this.ratings = ratings;
  }
  watch() {
    console.log("Watch Online");
  }
}
let rocky = new Movies("Rocky", 1976, ["Drama", "Sports"], {
  IMDb: "8.1 / 10",
  Metacritic: "70%"
});
console.log(rocky);
// Movies {
//     name: 'Rocky',
//         releaseYear: 1976,
//             genre: ['Drama', 'Sports'],
//                 ratings: { IMDb: '8.1 / 10', Metacritic: '70%' }
// }

rocky.watch();
//Watch Online

Here I have defined all the arguments inside the constructor.

Methods can be a part of the class while declarations can be added later to the created instance of the class, “objects”:

/*
above example
*/
rocky.buy = function() {
  console.log("Buy the Movie");
};
rocky.buy();
// Buy the Movie

Here this method is a part of the object and will not affect our original class.

Both classes and constructors imitate an object-oriented inheritance model to JavaScript, which is a prototype-based inheritance language.

Being familiar with classes is extremely helpful, as popular JavaScript libraries such as React make frequent use of the 

class
 syntax.

Previously published at https://medium.com/better-programming/three-different-ways-to-create-objects-in-javascript-d3595d693296