How to usethe Spread operator in Javascript
Using the spread operator { … }, merge properties from multiple objects into a new object or add new properties to an existing object in JavaScript.
Syntax:
let variablename1 = [...value];
Example: In this example, we are using the above-explained approach.
// Step 1: Create a new object
//with existing properties
const existingObject =
{ name: "Rishab Pant", age: 30 };
// Step 2: Add or override properties
//using the spread operator
const newObject = {
...existingObject,
city: "India",
occupation: "Cricketer",
};
console.log(newObject);
Output
{ name: 'Rishab Pant', age: 30, city: 'India', occupation: 'Cricketer' }
How to create object properties in JavaScript ?
JavaScript is built on an object-oriented framework. An object is a collection of properties, where each property links a key to a value. These properties are not in any specific order.
The value of a JavaScript property can be a method (function). Object properties can be updated, modified, added, or deleted. Sometimes, properties are static and cannot be changed. In this article, we will explore how to access and create object properties in JavaScript.
There are several methods that can be used to create object properties.
Table of Content
- Approach 1: Using the dot operator
- Approach 2: Using Square Bracket Notation
- Approach 3: Object Initializer (Literal) Syntax
- Approach 4: Object.assign() method
- Approach 5: Using the Spread operator
- Approach 6: Using the Object.defineProperties() method