'What do curly braces around a variable in a function parameter mean [duplicate]
I saw this code on a package:
const SortableList = SortableContainer(({items}) => {
return (
<ul>
{items.map((value, index) =>
<SortableItem key={`item-${index}`} index={index} value={value} />
)}
</ul>
);
});
What is happening to items by putting curly braces around it in the function parameters?
Solution 1:[1]
This question is likely a repost: What do {curly braces} around javascript variable name mean
But as an answer, it's destructuring assignment. If your object being passed in mirrors the variable being referenced, you can retrieve that specific field during assignment.
Solution 2:[2]
This is Destructuring Assignment.
In this example below, the variables "name", "sex" and "age" in curly braces "{}" extract the values "John", "Male" and "24" from "data" respectively:
*The variable names in curly braces "{}" must be same as the key names in "data"
const data = { name: "John", sex: "Male", age: 24 };
const { name, sex, age } = data;
console.log(name); // John
console.log(sex); // Male
console.log(age); // 24
If the variable names in curly braces "{}" are not same as the key names in "data", the values of "undefined" are assigned:
const data = { name: "John", sex: "Male", age: 24 };
const { myName, mySex, age } = data;
console.log(myName); // undefined
console.log(mySex); // undefined
console.log(age); // 24
The order of the variables in curly braces "{}" doesn't matter:
const data = { name: "John", sex: "Male", age: 24 };
const { age, sex, name } = data;
console.log(name); // John
console.log(sex); // Male
console.log(age); // 24
You can rename the variables in curly braces "{}":
const data = { name: "John", sex: "Male", age: 24 };
const { name: firstName, sex: gender, age } = data;
console.log(firstName); // John
console.log(gender); // Male
console.log(age); // 24
After renaming the variables in curly braces "{}", the original variables don't work and give error:
const data = { name: "John", sex: "Male", age: 24 };
const { name: firstName, sex: gender, age } = data;
console.log(name);
console.log(sex);
console.log(age);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 |
