Thursday, November 20, 2025
HomeLanguagesJavascriptHow to unpack array elements into separate variables using JavaScript ?

How to unpack array elements into separate variables using JavaScript ?

Given an array and the task is to unpack the value of the array into separate variables by using the preferred method using javascript.

We can unpack the array elements into separate variables by the following methods:

Approach 1: Destructuring Assignment

  • Store the elements of an array into an array variable.
  • Now use the ES6 script to declare a variable and unpack the value of the array into separate variables.

Example 1: This example declares a variable using the let keyword to unpack the array elements into separate variables. 

Javascript




const arr = [1, 2, 3, 4];
function GFG_Fun() {
    let [a, b, c, d] = arr;
    console.log(a);
    console.log(b);
    console.log(c);
    console.log(d);
}
GFG_Fun();


Output

1
2
3
4

Approach 2: Using Array.slice() Method

The Javascript arr.slice() method returns a new array containing a portion of the array on which it is implemented. The original remains unchanged.

Example:

Javascript




const array = [1, 2, 3, 4];
function GFG_Fun() {
    const a = array.slice(0, 1)[0];
    const b = array.slice(1, 2)[0];
    const c = array.slice(2, 3)[0];
    console.log(a);
    console.log(b);
    console.log(c);
}
GFG_Fun();


Output

1
2
3

Approach 3: Using the spread operator

The Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected. It allows us the privilege to obtain a list of parameters from an array. 

Example:

Javascript




const array = [1, 2, 3];
const [a, b, c] = [...array];
 
console.log(a);
console.log(b);
console.log(c);


Output

1
2
3

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32404 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6776 POSTS0 COMMENTS
Nicole Veronica
11924 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11994 POSTS0 COMMENTS
Shaida Kate Naidoo
6904 POSTS0 COMMENTS
Ted Musemwa
7160 POSTS0 COMMENTS
Thapelo Manthata
6860 POSTS0 COMMENTS
Umr Jansen
6846 POSTS0 COMMENTS