Home > Web Front-end > JS Tutorial > Destructuring in function parameters

Destructuring in function parameters

WBOY
Release: 2024-08-29 10:36:02
Original
705 people have browsed it

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
    }

  ];
Copy after login

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

  const cubes = geometriesRaw.map((cube)=>{
    <mesh position={[cube.x, cube.y, cube.z]}>
        <boxGeometry args={[cube.width, cube.height, cube.depth]} /> 
        <meshPhongMaterial color={cube.color} /> 
      </mesh>
  }) 

Copy after login

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})=>{
    <mesh position={[x, y, 0]}>
        <boxGeometry args={[width, 1, 1]} /> 
        <meshPhongMaterial color={color} /> 
      </mesh>
  }) 

Copy after login

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

The above is the detailed content of Destructuring in function parameters. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template