"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Destructuring in function parameters

Destructuring in function parameters

Published on 2024-11-08
Browse:712

Destructuring in function parameters

Let's say I have a project in three.js and I need some geometries, I will hardcode an array of objects that will contain their x,y, and z, values as well as their width, height, and depth values but this array could be coming from the server or third-party APIs =>

const geometriesRaw = [
    {
      color: 0x44aa88,
      x: 0,
      y: 1,
      z: 0,
      width: 1,
      height: 1,
      depth: 1
    },
    {
      color: 0x8844aa,
      x: -2,
      y: 1,
      z: 0,
      width: 1.5,
      height: 1.5,
      depth: 1.5
    }

  ];

Then I will render them using the Array. map function =>

  const cubes = geometriesRaw.map((cube)=>{
    
         
         
      
  }) 

In just a glance we can realize the verbosity of this code, repeating the argument cube every time.
Another red flag is the no clarity on what properties we're using from the array, for example, z is 0 in both cases and it will probably be zero in the vast majority of cases.
For our regular use case, we shouldn't expose this property to our function, this could also happen frequently with the depth property.

For that reason, the best option will be destructuring the properties coming from the array of objects as follows =>

 const cubes = geometriesRaw.map(({x,y, width, color})=>{
    
         
         
      
  }) 

Now we're just using x,y, width, color. This way we're implying that z, height, and depth are default properties inside our function and we don't need them from the data coming from our server or third-party

This way we're hiding properties for future devs that will interact with our cubes' constant, just showing them the ones we need from an external source and the ones we are setting as the default for better practice we can even write
const z = 0
...
inside our function to make it even clearer

Release Statement This article is reproduced at: https://dev.to/kevincoto/destructuring-in-function-parameters-5gkb?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3