Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax: const {} = variableName, can anyone explain or point me into the right direction [duplicate]

What does this syntax mean in JavaScript (ES6 probably):

const {} = variablename;

I'm currently trying to get a grip of React. In a lot of examples I came across that syntax. For example:

const {girls, guys, women, men} = state; 
like image 994
Angelo A Avatar asked Feb 15 '16 17:02

Angelo A


People also ask

What does const {} mean in JS?

In JavaScript, `const` means that the identifier can't be reassigned. (Not to be confused with immutable values. Unlike true immutable datatypes such as those produced by Immutable. js and Mori, a `const` object can have properties mutated.)

What does const {} mean in node JS?

Const is the variables declared with the keyword const that stores constant values. const declarations are block-scoped i.e. we can access const only within the block where it was declared. const cannot be updated or re-declared i.e. const will be the same within its block and cannot be re-declare or update.

Which is the correct syntax to declare a constant in JavaScript?

Naming a constant in JavaScript has some rules for naming a variable, keeping intact the const keyword, and global constants. If in case the keyword 'const' is removed, the identifier is represented as a variable. Hence to declare a constant variable, need to use the keyword 'const' instead of 'let.

Where can I use let and const?

As a general rule, you should always declare variables with const, if you realize that the value of the variable needs to change, go back and change it to let. Use let when you know that the value of a variable will change. Use const for every other variable.


1 Answers

First of all, this has nothing to do with React. It's part of ECMAScript 6 (or JavaScript 2015 if you prefer).

What you see here is called Destructuring assignment:

const {girls, guys, women, men} = state;  // Is the same as  const girls = state.girls; const guys = state.guys; const women = state.women; const men = state.men; 



You're probably going to encounter a similar patter while studying React:

import { methodA, methodB } from "my-module"; 

In this case you have a module called my-module that is exposing some functions. With the import {} from syntax you choose which functions you want to import. Note that this is not destructuring assignment although it works in a similar way.

like image 117
Giorgio Polvara - Gpx Avatar answered Sep 23 '22 13:09

Giorgio Polvara - Gpx