JavaScript Objects Quick Reference

Everything you need to know for working with JavaScript Objects

Any object in JavaScript is a collection of key-value pairs. The key, also known as a property, is a unique string that maps to a value which may be a Boolean, String or another object.

Let’s take a simple person object that contains properties like name, age and the employment status.

const person = {
  name: 'John',
  age: 21,
  gender: 'Male',
  employed: false,
};
  • Check if a property (or key) exists in an object
console.log('country' in person); // returns false
console.log('employed' in person); // returns true
console.log(person.hasOwnProperty('gender'));
  • Iterate over an object and print the key-value pairs
Object.keys(person).forEach((key) => {
  console.log(`${key}: ${person[key]}`);
});

Object.entries(person).forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});
  • Prevent new properties from being added to the object
Object.preventExtensions(person);
person.full_name = 'John Q Public';
console.log(person); // the full name property is not added
  • Check if new properties can be added to an object
Object.isExtensible(person);
delete person.name; // you can still delete properties
  • Prevent properties from getting added or deleted
Object.seal(person);
delete person.age;
console.log(person.age); // the property is not deleted
  • Check if properties can be added or deleted from any object
Object.isSealed(person);
  • Prevent properties from getting added, deleted or modified
Object.freeze(person);
  • Check if an object can be modified
Object.isFrozen(person);
  • Combine two objects (use default values)
const defaultPerson = {
  name: 'Unknown',
  country: 'Unknown',
};

const newPerson = {
  name: 'John',
  age: 21,
};

const mergedPerson = Object.assign(defaultPerson, newPerson);
console.log(mergedPerson);
  • Create a shallow clone of an object
const clone = Object.assign({}, person);
// changes to the clone will not modify the original object

Amit Agarwal is a web geek, solo entrepreneur and loves making things on the Internet. Google recently awarded him the Google Developer Expert and Google Cloud Champion title for his work on Google Workspace and Google Apps Script.

Awards & Recognition

Google Developer Expert

Google Developer Expert

Google awarded us the Developer Expert title recogizing our work in Workspace

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional title for 5 years in a row

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator award for technical expertise

Want to stay up to date?
Sign up for our email newsletter.

We will never send any spam emails. Promise 🫶🏻