The Modern JavaScript Objects Cheat Sheet

Updated: March 2, 2023 By: Khue Post a comment

This page provides a concise but comprehensive cheat sheet about objects in modern JavaScript.

Creating Objects

Object Literal

The object literal notation is the most common and concise way to create an object in JavaScript:

const person = {
  name: 'Wolf',
  age: 999,
  hobbies: ['reading', 'eating', 'gaming'],
  address: {
    city: 'West Sling Academy',
    country: 'The Lands Between'
  },
  sayHello() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

Constructor Function

Another way to create an object is to use a constructor function:

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.sayHello = function() {
    console.log(`Hello, my name is ${this.name}`);
  };
}

const person1 = new Person('Ranni The Witch', 300);

Class

ES6 introduced a class syntax for creating objects that is syntactic sugar over the constructor function syntax:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  sayHello() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const person1 = new Person('Bad Man', 123);

Accessing Object Properties

const person = {
  name: 'Turtle Pope',
  age: 321,
  address: {
    city: 'Atlanta',
    state: 'GA',
  },
};

console.log(person.name);
console.log(person['age']);
console.log(person.address.city);

We can access the properties of an object using either the dot notation or bracket notation. Dot notation is the preferred method for accessing properties when possible. However, bracket notation can be useful for accessing properties with special characters or properties that are dynamically generated.

Modifying Object Properties

const person = {
  name: 'Badman',
  age: 30,
  hobbies: ['reading', 'golf']
};

person.age = 40;
person.hobbies.push('traveling');
console.log(person); 
// Output: { name: 'Badman', age: 40, hobbies: ['reading', 'golf', 'traveling'] }

We can modify the properties of an object by assigning a new value to the property.

Deleting Properties

const person = {
  name: 'Badman',
  age: 30,
  hobbies: ['reading', 'golf']
};

delete person.age;
console.log(person); 
// Output: { name: 'Badman', hobbies: ['reading', 'golf'] }

Adding Methods to an Object

We can define methods on an object by assigning a function to a property:

const person = {
  name: 'Badman',
  age: 30,
  getFullName: function() {
    return `${this.name} XYZ`;
  }
};

console.log(person.getFullName()); 
// Output: Badman XYZ

Object Built-In Methods

Object.keys()

This method returns an array of keys of the enumerable properties of an object.

const obj = { a: 1, b: 2, c: 3 };
const keys = Object.keys(obj); // ["a", "b", "c"]

Iterating over object properties:

const obj = { a: 1, b: 2, c: 3 };
for (let key in obj) {
  console.log(`${key}: ${obj[key]}`);
}
// a: 1
// b: 2
// c: 3

Object.values()

This method returns an array of values of the enumerable properties of an object.

const obj = { a: 1, b: 2, c: 3 };
const values = Object.values(obj); // [1, 2, 3]

Object.entries()

This method returns an array of arrays, each containing a key-value pair of an object.

const obj = { a: 1, b: 2, c: 3 };
const entries = Object.entries(obj); // [["a", 1], ["b", 2], ["c", 3]]

Object.fromEntries()

This method returns an object from an array of key-value pairs.

const entries = [["a", 1], ["b", 2], ["c", 3]];
const obj = Object.fromEntries(entries); // { a: 1, b: 2, c: 3 }

Object.assign()

This method Copies the values of all enumerable properties from one or more source objects to a target object.

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const result = Object.assign(target, source); // { a: 1, b: 4, c: 5 }

Object.freeze()

This method prevents the modification of existing property attributes and values and prevents the addition of new properties.

const obj = { a: 1, b: 2 };
Object.freeze(obj);
obj.a = 3; // throws an error in strict mode

Object.seal()

This method seals an object, preventing new properties from being added and marking all existing properties as non-configurable.

const obj = { a: 1, b: 2 };
Object.seal(obj);
obj.a = 3; // can modify existing properties
obj.c = 4; // cannot add new properties
delete obj.b; // cannot delete existing properties

Object.hasOwnProperty()

Property existence check:

const hasProp = obj1.hasOwnProperty('name');

Object Destructuring

Object destructuring is a convenient way to extract properties from an object and assign them to variables.

const person = {
  name: 'Spiderman',
  age: 35,
  hobbies: ['talking', 'fighting', 'traveling']
};

const {name, age, hobbies} = person;

console.log(name, age, hobbies); 
// Output: Spiderman 35 ['talking', 'fighting', 'traveling']

Spread Operator

Shallow copy

const person1 = {
  name: 'Badman',
  age: 30,
  hobbies: ['reading', 'golf']
};

const person2 = { ...person1 };

person2.name = 'Mary';
person2.hobbies.push('traveling');

console.log(person1); 
// Output: { name: 'Badman', age: 30, hobbies: ['reading', 'golf', 'traveling'] }

console.log(person2); 
// Output: { name: 'Mary', age: 30, hobbies: ['reading', 'golf', 'traveling'] }

Merging Objects

const person1 = {
  name: 'Badman',
  age: 30
};

const person2 = {
  hobbies: ['reading', 'golf']
};

const merged = { ...person1, ...person2 };
console.log(merged); 
// Output: { name: 'Badman', age: 30, hobbies: ['reading', 'golf'] }

Object Comparison

In JavaScript, objects are compared by reference, not by value. Two objects are considered equal only if they reference the same object in memory. However, there are ways to compare the values of two objects.

Using JSON.stringify()

The JSON.stringify() method returns a JSON string representing an object, which can be compared with another JSON string.

const person1 = {
  name: 'Badman',
  age: 30,
  hobbies: ['reading', 'golf'],
};

const person2 = {
  name: 'Badman',
  age: 30,
  hobbies: ['reading', 'golf'],
};

console.log(person1 === person2); 
// Output: false

console.log(JSON.stringify(person1) === JSON.stringify(person2)); 
// Output: true

Comparing Properties

const person1 = {
  name: 'Badman',
  age: 30,
  hobbies: ['reading', 'golf']
};

const person2 = {
  name: 'Badman',
  age: 30,
  hobbies: ['reading', 'golf']
};

const compareObjects = (obj1, obj2) => {
  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);

  if (keys1.length !== keys2.length) {
    return false;
  }

  for (let key of keys1) {
    if (obj1[key] !== obj2[key]) {
      return false;
    }
  }

  return true;
};

console.log(compareObjects(person1, person2)); 
// Output: true

Deep Copy

Clone a deeply nested object:

const deepCopy = JSON.parse(JSON.stringify(obj1));

Final Words

Hope this cheat sheet is helpful to you for quickly looking up different aspects of objects in modern JavaScript. If you see anything that needs to be added or corrected, let me know by leaving comments.

If you need more detailed instructions and more concrete examples about JavaScript objects, continue reading other articles in this series.