E2EHIRING Logo
Jobs
Jobs
courses
Courses
mentorship
Mentorship
more
Moredropdown
E2EHIRING Logo
more
Jobs
Jobs
courses
Courses
mentorship
Mentorship
HomeSepratorIconBlogsSepratorIconJavaScript Spread OperatorSepratorIcon

JavaScript Spread Operator

Han SoloPriyanka Siddalingreddy
calendar30 Jun 2022
poster

JavaScript Spread Operator

The JavaScript spread operator (...) allows us to quickly copy all or part of an existing array or object into another array or object. 

Example

const num1 = [1,2,3,4];
const num2 = [5,6,7,8];
const numbers =  [...num1, ...num2];
console.log(numbers) // 1,2,3,4,5,6,7,8

ES6 provides a new operator called spread operator that consists of three dots (...). The spread operator allows you to spread out elements of an iterable object such as an array, map, or set. For example:

const odd = [1,3,5];
const combined = [2,4,6, ...odd];
console.log(combined); //[ 2, 4, 6, 1, 3, 5 ]

In this example, the three dots ( ...) located in front of the odd array is the spread operator. The spread operator (...) unpacks the elements of the odd array.

JavaScript spread operator and array manipulation

1. Constructing array literal

     The spread operator allows you to insert another array into the initialized array when you construct an array using the literal form. See      the following example: 

let initialChars = ['A', 'B'];
let chars = [...initialChars, 'C', 'D'];
console.log(chars); // ["A", "B", "C", "D"]

2. Concatenating arrays

    Also, you can use the spread operator to concatenate two or more arrays:

let numbers = [1, 2];
let nextNumbers = [3, 4];
let allNumbers = [...numbers, ...nextNumbers];
console.log(allNumbers); //[1, 2, 3, 4]

3. Copying an array 

    In addition, you can copy an array instance by using the spread operator:

let scores = [50, 70, 90];
let copiedScores = [...scores];
console.log(copiedScores); //[50,70,90]








Recent Posts

 Introduction to Java Programming: Basics and Fundamentals

Introduction to Java Programming: Basics and Fundamentals

Introduction to Web Technologies: HTML, CSS, and JavaScript

Introduction to Web Technologies: HTML, CSS, and JavaScript

Introduction of JavaScript

Introduction of JavaScript

Java/Kotlin : Interoperability & Benefits

Java/Kotlin : Interoperability & Benefits

Introduction of Bootstrap

Introduction of Bootstrap

copycopycopycopy

Han Solo

Recent Posts

 Introduction to Java Programming: Basics and Fundamentals

Introduction to Java Programming: Basics and Fundamentals

Introduction to Web Technologies: HTML, CSS, and JavaScript

Introduction to Web Technologies: HTML, CSS, and JavaScript

Introduction of JavaScript

Introduction of JavaScript

Java/Kotlin : Interoperability & Benefits

Java/Kotlin : Interoperability & Benefits

Introduction of Bootstrap

Introduction of Bootstrap