Skip to content

ES6 - Objects

In JavaScript, objects are fundamental data structures that store collections of key-value pairs. Keys are typically strings (or Symbols in ES6+), and values can be any data type, including other objects or functions (methods). ES6 introduced several enhancements to make working with objects more concise and powerful.

Object literals are the most common way to create objects, using curly braces {}.

  1. Shorthand Property Names: If a variable name is the same as the intended property key, you can omit the colon and value.
const name = "Alice";
const age = 30;
// ES5 way
// const personES5 = { name: name, age: age };
// ES6 shorthand
const person = { name, age };
console.log(person); // { name: "Alice", age: 30 }
  1. Shorthand Method Names: You can define methods more concisely.
// ES5 way
// const calculatorES5 = {
// add: function(a, b) { return a + b; }
// };
// ES6 shorthand
const calculator = {
add(a, b) {
return a + b;
},
subtract(a, b) { // Also an example of a shorthand method
return a - b;
}
};
console.log(calculator.add(5, 3)); // 8
  1. Computed Property Names: Allows you to use an expression for a property key within the object literal.
let propPrefix = "user";
const dynamicObject = {
[propPrefix + "Id"]: 123,
[propPrefix + "Name"]: "Bob",
[`${propPrefix}Role`]: "Admin" // Using template literal
};
console.log(dynamicObject); // { userId: 123, userName: "Bob", userRole: "Admin" }
  • Dot Notation: object.propertyName (when the property name is a valid identifier).
  • Bracket Notation: object['propertyName'] (when the property name is dynamic, a string with special characters, or a variable).
console.log(person.name); // "Alice"
console.log(dynamicObject['userId']); // 123
let keyToAccess = "userName";
console.log(dynamicObject[keyToAccess]); // "Bob"

While object literals are common, objects can also be created using constructor functions or ES6 classes.

1. new Object() Constructor (Less Common):

Section titled “1. new Object() Constructor (Less Common):”
const car = new Object();
car.make = "Ford";
car.model = "Mustang";
console.log(car.make); // "Ford"
// This is equivalent to: const car = {};

2. Custom Constructor Functions (Pre-ES6 Classes):

Section titled “2. Custom Constructor Functions (Pre-ES6 Classes):”
function Vehicle(make, model) {
this.make = make;
this.model = model;
this.displayInfo = function() {
console.log(`Vehicle: ${this.make} ${this.model}`);
};
}
const myVehicle = new Vehicle("Toyota", "Camry");
myVehicle.displayInfo(); // "Vehicle: Toyota Camry"

3. ES6 Classes (Preferred for complex objects):

Section titled “3. ES6 Classes (Preferred for complex objects):”
// See the 'ES6 - Classes' section for more details
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
const lion = new Animal("Leo");
lion.speak(); // "Leo makes a sound."

The Object constructor itself provides several useful static methods:

Copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object. This is a shallow copy.

const target = { a: 1, b: 2 };
const source1 = { b: 4, c: 5 };
const source2 = { d: 6 };
const merged = Object.assign(target, source1, source2);
console.log(target); // { a: 1, b: 4, c: 5, d: 6 } (target is modified)
console.log(merged); // { a: 1, b: 4, c: 5, d: 6 }
// Cloning an object (shallow clone)
const original = { x: 10, y: 20 };
const clone = Object.assign({}, original);
console.log(clone); // { x: 10, y: 20 }
clone.x = 100;
console.log(original.x); // 10 (original is not affected for primitive properties)

Creates a new object with the specified prototype object and optional properties.

const animalPrototype = {
greet() {
console.log(`Hello, I am a ${this.type}`);
}
};
const dog = Object.create(animalPrototype);
dog.type = "Dog";
dog.greet(); // "Hello, I am a Dog"

Returns an array of a given object’s own enumerable property names (strings).

Returns an array of a given object’s own enumerable property values.

Returns an array of a given object’s own enumerable string-keyed property [key, value] pairs.

const user = { id: 1, username: 'testuser', email: 'test@example.com' };
console.log(Object.keys(user)); // ["id", "username", "email"]
console.log(Object.values(user)); // [1, "testuser", "test@example.com"]
console.log(Object.entries(user)); // [["id", 1], ["username", "testuser"], ["email", "test@example.com"]]

Object.getPrototypeOf(obj) and Object.setPrototypeOf(obj, prototype) (ES6)

Section titled “Object.getPrototypeOf(obj) and Object.setPrototypeOf(obj, prototype) (ES6)”

Standard ways to get and set the prototype of an object. Object.setPrototypeOf should be used with caution due to performance implications.

The delete operator removes a property from an object.

const myObj = { a: 5, b: 12 };
delete myObj.a;
console.log(myObj); // { b: 12 }
console.log('a' in myObj); // false

Objects are reference types. Two distinct objects are never equal (=== or ==) even if they have the same properties, because they refer to different memory locations. Comparison only yields true if both variables point to the exact same object instance.

const obj1 = { name: "Tom" };
const obj2 = { name: "Tom" };
const obj3 = obj1;
console.log(obj1 === obj2); // false (different objects in memory)
console.log(obj1 === obj3); // true (obj3 refers to the same object as obj1)

A convenient way to extract properties from objects into distinct variables.

const employee = {
firstName: 'John',
lastName: 'Doe',
department: 'Engineering'
};
// Basic destructuring
const { firstName, department } = employee;
console.log(firstName); // "John"
console.log(department); // "Engineering"
// Destructuring with different variable names
const { lastName: surname } = employee;
console.log(surname); // "Doe"
// Destructuring with default values
const { country = "USA" } = employee;
console.log(country); // "USA"
// Destructuring in function parameters
function printEmployeeInfo({ firstName, department }) {
console.log(`${firstName} works in ${department}.`);
}
printEmployeeInfo(employee); // "John works in Engineering."

For further information on Object methods and features, refer to MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object