Skip to content

Objects and Classes in JavaScript

Object Literals

This is the most common way to create an object in JavaScript. An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}).

let obj = {
    key1: 'value1',
    key2: 'value2',
    key3: 'value3'
};

Accessing properties

You can access properties of an object using dot notation or bracket notation.

console.log(obj.key1);  // Outputs: value1
console.log(obj['key2']);  // Outputs: value2

Methods

Objects can also have functions as properties, which are called methods.

let obj = {
    sayHello: function() {
        console.log('Hello, World!');
    }
};

obj.sayHello();  // Outputs: Hello, World!

Constructor Function

You can define an object constructor function, and then create objects of the constructed type.

function Car(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
}

let myCar = new Car('Toyota', 'Corolla', 2005);

Prototypes

Every JavaScript object has a prototype. The prototype is also an object, and all objects inherit their properties and methods from their prototype.

Car.prototype.color = null;
myCar.color = 'black';

ES6 Classes

ES6 introduced a class keyword to create objects, which is syntactic sugar over JavaScript’s existing prototype-based inheritance.

class Car {
    constructor(make, model, year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }
}

let myCar = new Car('Toyota', 'Corolla', 2005);

Object Destructuring

ES6 introduced destructuring, which allows you to unpack values from arrays, or properties from objects, into distinct variables.

let {make, model, year} = myCar;

Spread Operator

The spread operator (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

let car1 = {color: 'red', wheels: 4};
let car2 = {...car1, color: 'blue'};  // car2 is now {color: 'blue', wheels: 4}