How many ways to Create Objects in JavaScript

How many ways to Create Objects in JavaScript

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’s get this started.

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. Classes.

You may also like: Top 8 Trends and Tools Front-End JavaScript for 2020.

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 the 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]
// }
view rawobjectnew3.js hosted with ❤ by GitHub

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

Using ES6 Classes to Create Objects

This method is similar to using new with the user-defined function constructor. Classes are the primary components of Object-Orientediented 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%' }
// }

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

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  make frequent use of the class syntax.

Further Reading

Thank you for reading. Hope this tutorial will surely help and you! Please share if you liked it!

javascript es6 web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.