This content originally appeared on DEV Community and was authored by Kevin Coto🚀💡
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)=>{
<mesh position={[cube.x, cube.y, cube.z]}>
<boxGeometry args={[cube.width, cube.height, cube.depth]} />
<meshPhongMaterial color={cube.color} />
</mesh>
})
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>
})
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
This content originally appeared on DEV Community and was authored by Kevin Coto🚀💡
Kevin Coto🚀💡 | Sciencx (2024-08-28T03:04:44+00:00) Destructuring in function parameters. Retrieved from https://www.scien.cx/2024/08/28/destructuring-in-function-parameters/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.