Search code examples
javascriptfunctiondestruction

Destructuring declaration bug with the value


I can not understand why after destructuring assignment, items prop does not equal Gorilla.

It will be used after deleting the main prop items: "Piggi" in the origin object options. I do not understand why...

    'use strict';
    
    let options = {
      size: 100,
      items: "Piggi"
    }
    
    let { title="Menu", items:w="Gorilla", size } = options;
    
    let a = title;
    let b = w;
    console.log(a + " - " + b);  // must be "Menu - Gorilla"


Solution

  • In the destructuring declaration with initialization here:

    let { items:w = "Gorilla" } = options;
    

    the syntax means to declare a variable called "w", whose value should be initialized to the value of the property called "items" in the object referenced by "options", or if there is no such property then to the string "Gorilla".

    In your case, then, the variable "w" is initialized to the value of the "items" property in the original object.

    If you don't want to take the value from the source object, then don't:

    let w = "Gorilla";