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;
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.)
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With