Search code examples
javascriptarraysdestructuring

Automatic Array destructuring within function parameter?


function getValues(param=[width, height]) {
   return `Width= ${width}, Height = ${height}`;
  }

The cod above doesn't work because "width" and "height" are not defined within the function body

But, the function definition below works fine and I am not quite clear why the array parameters are automatically destructured to its elements below, while it doesn't so in the above case.

 function getValues([width, height]) {
   return `Width= ${width}, Height = ${height}`;
  }

I would appreciate for any clarification here. Thank you.


Solution

  • Using = in arguments, is basically setting default value in case of missing parameter (Default parameters). Once, you call the function with missing parameter(s) or undefined as parameter, default value is set against the argument. In your example, if you pass any argument, the default value [width, height] will be ignored and if you do not, Uncaught ReferenceError will be thrown as width and height does not exist (provided not defined globally or in the function scope).

    The following will give you value for width and height as the first parameter is assigned to width and second to height.

    function getValues(width, height, param=[width, height]) {
       console.log(param); // [5,6]
       return `Width= ${width}, Height = ${height}`;
    }
      
    console.log(getValues(5,6));

    But, the function definition below works fine and I am not quite clear why the array parameters are automatically destructured to its elements below, while it doesn't so in the above case.

    This is in-accordance to the rules of Destructuring. Where if a parameter is an array, you can assign them into different variables based on index. e.g. here the first value in the array will be assigned to width and the second value will be assigned to height.

    function getValues([width, height]) {
      return `Width= ${width}, Height = ${height}`;
    }
    
    console.log(getValues([5, 6]));