Sunday, November 28, 2021

Spread operator in javascript

The spread operator (...) in JavaScript (introduced in ES6) lets you expand elements of an array, object properties, or iterable values into individual elements.

1. Spread with Arrays

Used to copy or combine arrays.

const arr1 = [1, 2, 3];

// Copy array
const arr2 = [...arr1];

console.log(arr2); // [1, 2, 3]

Combine arrays:

const a = [1, 2];
const b = [3, 4];

const combined = [...a, ...b];
console.log(combined); // [1, 2, 3, 4]

2. Spread with Objects

Used to copy or merge objects.

const user = {
name: "Lokman",
age: 25
};

const copy = {...user};
console.log(copy);

Merge objects:

const obj1 = {name: "Lokman"};
const obj2 = {age: 25};

const merged = {...obj1, ...obj2};

console.log(merged);
// {name: "Lokman", age: 25}
Spread does not modify the original array/object (it creates a shallow copy).

No comments:

Post a Comment

Javascript module

JavaScript Modules (ES6) let you split code into multiple files and reuse code cleanly. Main keywords: export → make something available...