Progress8 of 20 topics

40% complete

JavaScript Objects

Objects are one of the most powerful and flexible data types in JavaScript. They allow you to store collections of related data and functionality together in a structured way. If you've worked with arrays, think of objects as similar but with named properties instead of indexed positions.

Real-World Analogy

Think of a JavaScript object like a business card:

  • It contains different pieces of information (properties) about a person or entity
  • Each piece of information has a name (key) and a value
  • You can easily add, remove, or update information
  • You can access specific information by its name

Creating Objects

There are several ways to create objects in JavaScript.

Object Literals

The most common way to create an object is using an object literal, which is a comma-separated list of key-value pairs enclosed in curly braces.

JavaScript
1// Object literal syntax
2let person = {
3 firstName: "John",
4 lastName: "Doe",
5 age: 30,
6 email: "john.doe@example.com",
7 isEmployed: true
8};
9
10console.log(person); // Displays the entire object

Using the Object Constructor

You can also create an empty object and then add properties to it.

JavaScript
1// Empty object using constructor
2let car = new Object();
3
4// Adding properties
5car.make = "Toyota";
6car.model = "Corolla";
7car.year = 2022;
8car.isElectric = false;
9
10console.log(car); // {make: "Toyota", model: "Corolla", year: 2022, isElectric: false}

Accessing Object Properties

There are two main ways to access object properties: dot notation and bracket notation.

JavaScript
1// Accessing properties using dot notation
2let person = {
3 firstName: "John",
4 lastName: "Doe",
5 age: 30
6};
7
8console.log(person.firstName); // "John"
9console.log(person.age); // 30
10
11// Accessing properties using bracket notation
12console.log(person["lastName"]); // "Doe"
13
14// Bracket notation is useful when property names are stored in variables
15let propertyName = "age";
16console.log(person[propertyName]); // 30
17
18// Bracket notation is required for property names with spaces or special characters
19let product = {
20 "product name": "Laptop",
21 "product-id": "LP12345",
22 "price ($)": 999.99
23};
24
25console.log(product["product name"]); // "Laptop"
26console.log(product["price ($)"]); // 999.99

Dot vs. Bracket Notation

Use dot notation when you know the exact property name and it's a valid identifier (no spaces, doesn't start with a number, etc.).

Use bracket notation when:

  • The property name is stored in a variable
  • The property name has spaces or special characters
  • The property name starts with a number

Modifying Objects

Objects are mutable, which means you can change their properties after creation.

JavaScript
1// Changing property values
2let person = {
3 name: "John",
4 age: 30
5};
6
7person.name = "Jane";
8person["age"] = 28;
9
10console.log(person); // {name: "Jane", age: 28}
11
12// Adding new properties
13person.email = "jane@example.com";
14person["isEmployed"] = true;
15
16console.log(person); // {name: "Jane", age: 28, email: "jane@example.com", isEmployed: true}
17
18// Deleting properties
19delete person.age;
20
21console.log(person); // {name: "Jane", email: "jane@example.com", isEmployed: true}

Object Methods

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

JavaScript
1// Object with methods
2let person = {
3 firstName: "John",
4 lastName: "Doe",
5
6 // Method defined using function keyword
7 getFullName: function() {
8 return this.firstName + " " + this.lastName;
9 },
10
11 // Shorthand method syntax (ES6)
12 greet() {
13 return "Hello, my name is " + this.getFullName();
14 }
15};
16
17// Calling object methods
18console.log(person.getFullName()); // "John Doe"
19console.log(person.greet()); // "Hello, my name is John Doe"
20
21// Adding a method after object creation
22person.introduce = function(greeting) {
23 return `${greeting}, I'm ${this.firstName}!`;
24};
25
26console.log(person.introduce("Hi there")); // "Hi there, I'm John!"

The 'this' Keyword

In object methods, this refers to the object that the method belongs to.

JavaScript
1// Using 'this' in object methods
2let calculator = {
3 value1: 0,
4 value2: 0,
5
6 setValue(a, b) {
7 this.value1 = a;
8 this.value2 = b;
9 },
10
11 add() {
12 return this.value1 + this.value2;
13 },
14
15 multiply() {
16 return this.value1 * this.value2;
17 }
18};
19
20calculator.setValue(5, 3);
21console.log(calculator.add()); // 8
22console.log(calculator.multiply()); // 15

Be Careful with Arrow Functions

Arrow functions don't have their own this value. Instead, they inherit this from the surrounding code. This can cause unexpected behavior when used as object methods.

JavaScript
// Regular function works as expected
let person1 = {
name: "John",
greet: function() {
return "Hello, I'm " + this.name;
}
};
console.log(person1.greet()); // "Hello, I'm John"
// Arrow function doesn't work as expected
let person2 = {
name: "Jane",
greet: () => {
return "Hello, I'm " + this.name; // 'this' is not the person2 object
}
};
console.log(person2.greet()); // "Hello, I'm undefined"

Object Properties in Depth

Property Existence Check

You can check if an object has a specific property using different methods.

JavaScript
1let person = {
2 name: "John",
3 age: 30,
4 hobbies: null
5};
6
7// Using the in operator
8console.log("name" in person); // true
9console.log("address" in person); // false
10
11// Using hasOwnProperty method
12console.log(person.hasOwnProperty("age")); // true
13console.log(person.hasOwnProperty("toString")); // false (inherited property)
14
15// Comparing with undefined
16console.log(person.name !== undefined); // true
17console.log(person.address !== undefined); // false
18
19// Be careful with properties that have null or undefined values
20console.log(person.hobbies); // null (property exists but has null value)
21console.log(person.hobbies !== undefined); // true (property exists)

Property Attributes

Object properties have attributes that control how they behave. You can modify these usingObject.defineProperty().

JavaScript
1let product = {
2 name: "Laptop"
3};
4
5// Define a property with custom attributes
6Object.defineProperty(product, "price", {
7 value: 999.99,
8 writable: false, // Can't change the value
9 enumerable: true, // Shows up in loops
10 configurable: false // Can't delete or change attributes
11});
12
13// Try to change the price (won't work)
14product.price = 899.99;
15console.log(product.price); // Still 999.99
16
17// Define a property with a getter
18Object.defineProperty(product, "priceWithTax", {
19 get: function() {
20 return this.price * 1.1; // 10% tax
21 },
22 enumerable: true
23});
24
25console.log(product.priceWithTax); // 1099.989

Object Destructuring

Object destructuring allows you to extract properties from objects and assign them to variables.

JavaScript
1// Basic destructuring
2let person = {
3 firstName: "John",
4 lastName: "Doe",
5 age: 30,
6 address: {
7 city: "New York",
8 country: "USA"
9 }
10};
11
12// Extract properties into variables
13let { firstName, lastName, age } = person;
14
15console.log(firstName); // "John"
16console.log(lastName); // "Doe"
17console.log(age); // 30
18
19// Using different variable names
20let { firstName: fName, lastName: lName } = person;
21console.log(fName); // "John"
22console.log(lName); // "Doe"
23
24// Default values
25let { zipCode = "10001" } = person;
26console.log(zipCode); // "10001" (default value since it doesn't exist)
27
28// Nested destructuring
29let { address: { city, country } } = person;
30console.log(city); // "New York"
31console.log(country); // "USA"
32
33// Rest pattern
34let { firstName: name, ...details } = person;
35console.log(name); // "John"
36console.log(details); // {lastName: "Doe", age: 30, address: {city: "New York", country: "USA"}}

Object Methods and Operations

JavaScript provides several built-in methods to work with objects.

Object.keys()

Returns an array of an object's own enumerable property names.

JavaScript
let person = {
name: "John",
age: 30,
city: "New York"
};
let keys = Object.keys(person);
console.log(keys); // ["name", "age", "city"]

Object.values()

Returns an array of an object's own enumerable property values.

JavaScript
let person = {
name: "John",
age: 30,
city: "New York"
};
let values = Object.values(person);
console.log(values); // ["John", 30, "New York"]

Object.entries()

Returns an array of [key, value] pairs.

JavaScript
let person = {
name: "John",
age: 30
};
let entries = Object.entries(person);
console.log(entries);
// [["name", "John"], ["age", 30]]
// Useful for iterating
for (let [key, value] of entries) {
console.log(`${key}: ${value}`);
}

Object.assign()

Copies properties from one or more source objects to a target object.

JavaScript
let person = {
name: "John",
age: 30
};
let details = {
job: "Developer",
age: 31 // Will override
};
Object.assign(person, details);
console.log(person);
// {name: "John", age: 31, job: "Developer"}

Shallow vs. Deep Copying

When working with objects, it's important to understand the difference between shallow and deep copying.

JavaScript
1// Reference copy (not a real copy)
2let person = {
3 name: "John",
4 address: {
5 city: "New York",
6 country: "USA"
7 }
8};
9
10let referenceCopy = person; // Both variables point to the same object
11referenceCopy.name = "Jane";
12
13console.log(person.name); // "Jane" (original also changed)
14
15// Shallow copy (using spread operator)
16let shallowCopy = { ...person };
17shallowCopy.name = "Alice"; // This won't affect the original
18
19// But nested objects are still shared
20shallowCopy.address.city = "Boston";
21console.log(person.address.city); // "Boston" (original nested object changed)
22
23// Deep copy (for simple objects)
24let deepCopy = JSON.parse(JSON.stringify(person));
25deepCopy.address.city = "Chicago";
26console.log(person.address.city); // "Boston" (original not affected)

Deep Copy Limitations

The JSON.parse(JSON.stringify()) method has limitations:

  • It doesn't work with functions, undefined values, or circular references
  • It loses special types like Date objects (converts to strings)
  • For complex objects, consider using libraries like Lodash's cloneDeep

Object Iteration

There are several ways to iterate over an object's properties.

JavaScript
1let person = {
2 name: "John",
3 age: 30,
4 job: "Developer",
5 city: "New York"
6};
7
8// Using for...in loop (includes inherited properties)
9for (let key in person) {
10 if (person.hasOwnProperty(key)) { // Check for own properties
11 console.log(key + ": " + person[key]);
12 }
13}
14
15// Using Object.keys()
16Object.keys(person).forEach(key => {
17 console.log(key + ": " + person[key]);
18});
19
20// Using Object.entries() (ES2017)
21for (let [key, value] of Object.entries(person)) {
22 console.log(key + ": " + value);
23}

Practice Exercises

Try these exercises to reinforce your understanding of JavaScript objects:

JavaScript
// 1. Create an object representing a book with properties for title, author,
// year, and a method that returns the book's age (current year - publication year)
// 2. Create a function that takes an object and returns a new object with the
// same properties but with all string values converted to uppercase
// 3. Create a function that merges two objects, with the second object's
// properties overriding the first if there are conflicts
// 4. Create a function that takes an array of objects and a property name,
// and returns an array sorted by that property
// 5. Create a function that filters an array of objects based on a condition
// (e.g., all people over 30 years old)

Summary

In this tutorial, you've learned:

  • How to create and access objects
  • How to add, modify, and delete object properties
  • How to work with object methods and the this keyword
  • How to check for property existence
  • How to use object destructuring
  • How to use built-in object methods like Object.keys(), Object.values(), and Object.entries()
  • How to copy objects and understand the difference between shallow and deep copying
  • How to iterate over object properties

Objects are fundamental to JavaScript programming and are used extensively in real-world applications. Understanding how to work with objects effectively will help you build more organized and maintainable code.

Related Tutorials

Learn about arrays and how to work with collections of data.

Learn more

Learn how to create and use functions in JavaScript.

Learn more

Learn about more specialized data structures in JavaScript.

Learn more