Manipulating Object Properties

Tutorial 4 of 5

1. Introduction

In this tutorial, we aim to provide a concise overview of manipulating properties of JavaScript objects. We'll focus on how to add, update, and delete properties, exploring the key concepts involved.

By the end of this tutorial, you will be able to:

  • Understand basic principles of JavaScript objects
  • Manipulate properties of JavaScript objects (add, update, and delete)

Before we begin, ensure you are familiar with JavaScript basics, particularly variables, data types, and functions.

2. Step-by-Step Guide

JavaScript objects are mutable, meaning they can be changed after creation. Properties can be added, updated, and deleted.

Adding Properties: To add a new property to an object, simply assign a value to a new property name.

let obj = {}; // an empty object
obj.newProp = "Hello"; // adds a new property 'newProp' with value 'Hello'

Updating Properties: Updating a property is similar to adding - simply assign a new value to an existing property.

obj.newProp = "Hi"; // updates 'newProp' value to 'Hi'

Deleting Properties: To delete a property, we use the delete operator.

delete obj.newProp; // removes 'newProp' from object

Remember, trying to access a property that doesn't exist will return undefined.

3. Code Examples

Let's manipulate some properties!

// Create an object
let person = {
  name: "John Doe",
  age: 30
};

// Add a new property
person.job = "Developer";
console.log(person.job); // Expected output: "Developer"

// Update a property
person.name = "Jane Doe";
console.log(person.name); // Expected output: "Jane Doe"

// Delete a property
delete person.age;
console.log(person.age); // Expected output: undefined

4. Summary

We've covered the basics of JavaScript object property manipulation. We've learned how to add, update, and delete properties. Remember to use the dot notation for property manipulation, and that accessing a non-existent property returns undefined.

Continue learning by exploring built-in object methods, like Object.keys(), Object.values(), and Object.entries().

5. Practice Exercises

Exercise 1: Create a car object with properties: brand, model, and year. Then, add a color property.

Exercise 2: Update the year property of the car object to the current year.

Exercise 3: Delete the model property from the car object.

Solutions:

// Exercise 1
let car = {
  brand: "Tesla",
  model: "Model S",
  year: 2018
};
car.color = "Red";

// Exercise 2
car.year = new Date().getFullYear();

// Exercise 3
delete car.model;

Keep practicing by creating and manipulating your own objects. Happy coding!