Array Destructuring

11 0 0
                                        

Data structure is a technique used to manage data efficiently. One example is array. In array, you structuring the same data type of values in order using numbered keys starting from zero. You can set and get the values easily using the keys.

syntax:

let arrayName = [value1, value2, value3, value4, value5];

Destructuring does the opposite. Instead of structuring them, you are splitting them. What happens is you are assigning each value to the variables you declared. In case, the variables length is less than the values length, the other values will be ignored. In case, the variables length is greater than the values length, the value of those variables that exceed will be undefined. 

syntax 1:

let [var1, var2, var3] = arrayName;

    - var1 = value1, var2 = value2, var3 = value3

    - other values without assigned variables will be ignored.

syntax2: (using varargs symbol ...)

let [var1, ...var2] = arrayName;

    - var1 = value1

    - var2 = all the remaining values in array form

syntax3: (using default values)

let[var1="a", var2="b"] = arrayName;

    - var1 = either a or value1 if value1 is not empty

   - var2 = either b or value2 if value2 is not empty

    -other values without assigned variables will be ignored.


====================

let book1 = {

    title: "Reincarnated as a Slime",

    author: "Rimuru Senpai",

    published: 2021,

    main_type: "Demon Slime",

    main_character: "Rimuru Tempest" 

}

function displayYourBook1(){

    let array1 = Object.keys(book1);

    let [x, y, ...z] = array1;

    document.writeln('x: ${x}');

    document.writeln('y: ${y}');

    document.writeln('z: ${z}');

}

====================

HTML:

displayYourBook1()

Result:

x: title y: author z: published,main_type,main_character



Javascript ProgrammingWhere stories live. Discover now