Open In App

Creating objects in JavaScript

Last Updated : 13 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

An object in JavaScript is a collection of key-value pairs, where keys are strings (properties) and values can be any data type. Objects can be created using object literals, constructors, or classes. Properties are defined with key-value pairs, and methods are functions defined within the object, enabling encapsulation and organization of data and behavior.

These are the following 4 ways:

Creating object with a constructor

One of the easiest ways to instantiate an object is in JavaScript. Constructor is nothing but a function and with the help of a new keyword, the constructor function allows to creation of multiple objects of the same flavor as shown below: 

Example: This example shows the implementation of the above-explained approach.

javascript
// Simple function
function vehicle(name, maker, engine) {
    this.name = name;
    this.maker = maker;
    this.engine = engine;
}
// New keyword to create an object
let car = new vehicle('GT', 'BMW', '1998cc');
// Property accessors
console.log(car.name);
console.log(car.maker);
console.log(car['engine']);

Output
GT
BMW
1998cc

Explanation:

  • Class Components: A class in OOP has parameters and member functions, encapsulating attributes and behaviors.
  • Constructor Function: In a class method, parameters (e.g., name, maker, engine) use this to differentiate between class attributes and argument values.
  • Object Creation: Create an object (e.g., obj) from the class, initialize it, and call its methods to use the class functionality.

Using object literals

Using object literals to create objects in JavaScript involves defining an object directly with key-value pairs inside curly braces {}. This method is concise and straightforward, allowing you to quickly create objects with properties and methods, enhancing code readability.

Example: This example shows the implementation of the above-explained approach.

javascript
// Creating js objects with object literal
let car = {
    name: 'GT',
    maker: 'BMW',
    engine: '1998cc'
};
// Property accessor
console.log(car.name); //dot notation
console.log(car['maker']); //bracket notation

Output
GT
BMW

Explanation:

  • In the above code example we Created a car object using an object literal with properties like name, maker, and engine.
  • Used dot notation and bracket notation to access properties of the car object.

Now let’s see how we can add more properties to an already defined object: 

javascript
let car = {
    name: 'GT',
    maker: 'BMW',
    engine: '1998cc'
};
// Adding property to the object
car.brakesType = 'All Disc';
console.log(car);

Output
{ name: 'GT', maker: 'BMW', engine: '1998cc', brakesType: 'All Disc' }

 Methods can also be part of the object while creation or can be added later like properties as shown below: 

javascript
// Adding methods to the car object
let car = {
    name : 'GT',
    maker : 'BMW',
    engine : '1998cc',
    start : function(){
        console.log('Starting the engine...');
    }
};
car.start();
// Adding method stop() later to the object
car.stop = function() {
    console.log('Applying Brake...');  
}
car.stop();

Output
Starting the engine...
Applying Brake...

Explanation: In the above code start method was added to the car object and later called by the car.start() and also the stop method was added too after the object was already declared.  

Creating object with Object.create() Method

The Object.create() method in JavaScript creates a new object using an existing object as its prototype. This approach allows the new object to inherit properties and methods from the prototype object, enabling inheritance-like behavior. It’s useful for creating objects with shared behaviors while maintaining unique properties.

Example: This example shows the implementation of the above-explained approach.

javascript
const coder = {
    isStudying : false,
    printIntroduction : function(){
        console.log(`My name is ${this.name}. Am I studying?: ${this.isStudying}`);
    }
};
const me = Object.create(coder);
me.name = 'Mukul';
me.isStudying = true;
me.printIntroduction();

Output
My name is Mukul. Am I studying?: true

Using es6 classes

Using ES6 classes to create objects in JavaScript involves defining a class with a constructor to initialize properties and methods. Objects are then instantiated from the class using the new keyword, offering a more structured and OOP-like approach to object creation.

Example: This example the Vehicle class creates objects with name, maker, and engine properties. car1 is an instance with name set to GT.

javascript
// Using es6 classes
class Vehicle {
  constructor(name, maker, engine) {
    this.name = name;
    this.maker =  maker;
    this.engine = engine;
  }
}

let car1 = new Vehicle('GT', 'BMW', '1998cc');

console.log(car1.name);  //GT

Output
GT


Next Article

Similar Reads