Code Highlights logo

Learn

Objects

Property Assignment (assign and delete)

1. Object.assign()

The Object.assign() method allows us to copy the values of all enumerable properties from one or more source objects to a target object. It takes in a target object as the first parameter and one or more source objects as subsequent parameters. The method then returns the modified target object.

1// Create a target object
2const target = {};
3
4// Create a source object
5const source = { name: 'John', age: 25 };
6
7// Assign properties from source object to target object
8Object.assign(target, source);
9
10console.log(target);
11// Output: { name: 'John', age: 25 }

2. Deleting Properties

To delete a property from an object, we can use the delete keyword followed by the object name and the property name.

1// Create an object
2const car = {
3 brand: 'Toyota',
4 model: 'Camry',
5 year: 2021
6};
7
8// Delete the 'year' property
9delete car.year;
10
11console.log(car);
12// Output: { brand: 'Toyota', model: 'Camry' }

It is important to note that deleting a property removes the property completely from the object, including its value and any associated methods.


Instructions

1.

Inside the car object, add a new property called color and set its value to "blue".

2.

Delete the year property from the car object.

Sign up to start coding

Already have an account?

Sign In

Course content