What do curly braces around a variable in a function parameter mean

12.5k views Asked by At

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?

3

There are 3 answers

0
lawls544 On BEST ANSWER

This is destructuring assignment syntax.

As another example, the following two lines of code are equal:

const { items } = args

const items = args.items

Simply put, it is a simplified way of accessing specific field of a given variable for further use in that scope.

In your original example, it is declaring a variable items for use in the function body that is the items field of that first argument.

const SortableList = SortableContainer(({items}) => {
    // do stuff with items here

is equal to

const SortableList = SortableContainer((input) => {
    const items = input.items
    // do stuff with items here
0
Blake Geraci On

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.

0
Super Kai - Kazuya Ito On

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);