What does the syntax let = { as:comp, ...props } = props; mean? [duplicate] - javascript

I haven't seen this syntax before and am wondering what it's all about.
var { Navigation } = require('react-router');
The brackets on the left are throwing a syntax error:
unexpected token {
I'm not sure what part of the webpack config is transforming or what the purpose of the syntax is. Is it a Harmony thing? Can someone enlighten me?

It's called destructuring assignment and it's part of the ES2015 standard.
The destructuring assignment syntax is a JavaScript expression that
makes it possible to extract data from arrays or objects using a
syntax that mirrors the construction of array and object literals.
Source: Destructuring assignment reference on MDN
Object destructuring
var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true
// Assign new variable names
var {p: foo, q: bar} = o;
console.log(foo); // 42
console.log(bar); // true
Array destructuring
var foo = ["one", "two", "three"];
// without destructuring
var one = foo[0];
var two = foo[1];
var three = foo[2];
// with destructuring
var [one, two, three] = foo;

This is destructuring assignment. It's a new feature of ECMAScript 2015.
var {
AppRegistry,
StyleSheet,
Text,
View,
} = React;
Is the equivalent to:
var AppRegistry = React.AppRegistry;
var StyleSheet = React.StyleSheet;
var Text = React.Text;
var View = React.View;

var { Navigation } = require('react-router');
... uses destructuring to achieve the same thing as ...
var Navigation = require('react-router').Navigation;
... but is far more readable.

It's a new feature in ES6 to destructure objects.
As we all know that there is an assignment operation taking place here, which means right side value is getting assigned to left side variable.
var { Navigation } = require('react-router');
In this case require('react-router') method returns an object with key-value pair, something like:
{ Navigation: function a(){},
Example1: function b(){},
Example2: function c(){}
}
And if we would like to take one key in that returned object say Navigation to a variable we can use Object destructuring for that.
This will only be possible only if we have the key in hand.
So after the assignment statement, local variable Navigation will contain function a(){}
Another example looks like this.
var { p, q } = { p: 1, q:2, r:3, s:4 };
console.log(p) //1;
console.log(q) //2;

instead of
const salary = personnel.salary
const sex = personnel.sex
const age = personnel.age
simply
const {salary, age, sex} = personnel

Related

how to understand this JavaScript code output? [duplicate]

When I study electron, I found 2 ways of getting BrowserWindow object.
const {BrowserWindow} = require('electron')
and
const electron = require('electron')
const BrowserWindow = electron.BrowserWindow
What is the difference between const and const {} in JavaScript?
I can't understand why the const {} can work. Do I miss anything important about JS?
The two pieces of code are equivalent but the first one is using the ES6 destructuring assignment to be shorter.
Here is a quick example of how it works:
const obj = {
name: "Fred",
age: 42,
id: 1
}
//simple destructuring
const { name } = obj;
console.log("name", name);
//assigning multiple variables at one time
const { age, id } = obj;
console.log("age", age);
console.log("id", id);
//using different names for the properties
const { name: personName } = obj;
console.log("personName", personName);
const {BrowserWindow} = require('electron')
Above syntax uses ES6. If you have an object defined as:
const obj = {
email: "hello#gmail.com",
title: "Hello world"
}
Now if we want to assign or use email and title field of obj then we don't have to write the whole syntax like
const email = obj.email;
const title = obj.title;
This is old school now.
We can use ES6 Destructuring assignment i.e., if our object contains 20 fields in obj object then we just have to write names of those fields which we want to use like this:
const { email,title } = obj;
This is ES6 syntax-simpler one
It will automatically assign email and title from obj, just name has to be correctly stated for required field.
This is one of the new features in ES6. The curly braces notation is a part of the so called destructuring assignment. What this means is that, you no longer have to get the object itself and assign variables for each property you want on separate lines. You can do something like:
const obj = {
prop1: 1,
prop2: 2
}
// previously you would need to do something like this:
const firstProp = obj.prop1;
const secondProp = obj.prop2;
console.log(firstProp, secondProp);
// etc.
// however now you can do this on the same line:
const {prop1, prop2} = obj;
console.log(prop1, prop2);
As you have seen in the end the functionality is the same - simply getting a property from an object.
There is also more to destructuring assignment - you can check the entire syntax in MDN: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Other answers are good enough. I would suggest some useful features of Destructuring assignment
Firstly, Let's look at the following define:
The destructuring assignment syntax is a JavaScript expression that
makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Features:
Destructure an array, index of each item in array act as property (Due to an Array is an object in JavaScript)
> const {0: first, 1: second} = [10, 20]
console.log(first); // 10
console.log(second); // 20
Combine with Spread ... operator
> {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
console.log(a); // 10
console.log(b); // 20
console.log(rest ); // {c: 30, d: 40}
Default values
const {a = 10, b = 20} = {a: 1};
console.log(a); // 1
console.log(b); // 20
Assigning to new variable names
const {p: a, q: b} = {p: 10, q: 20};
console.log(a); // 10
console.log(b); // 20

Destructuring declaration bug with the value

I can not understand why after destructuring assignment, items prop does not equal Gorilla.
It will be used after deleting the main prop items: "Piggi" in the origin object options. I do not understand why...
'use strict';
let options = {
size: 100,
items: "Piggi"
}
let { title="Menu", items:w="Gorilla", size } = options;
let a = title;
let b = w;
console.log(a + " - " + b); // must be "Menu - Gorilla"
In the destructuring declaration with initialization here:
let { items:w = "Gorilla" } = options;
the syntax means to declare a variable called "w", whose value should be initialized to the value of the property called "items" in the object referenced by "options", or if there is no such property then to the string "Gorilla".
In your case, then, the variable "w" is initialized to the value of the "items" property in the original object.
If you don't want to take the value from the source object, then don't:
let w = "Gorilla";
When you analyze the code, you get three techniques working here:
short hand properties
{ foo, bar }
for
{ foo: foo, bar: bar}
default values
{ foo = 42 }
which is
{ foo: foo = 42 }
change of the target in the Object Property Assignment Pattern [You Don't Know JS: ES6 & Beyond, Chapter 2: Syntax]:
The syntactic pattern here is source: target (or value: variable-alias).
{ foo: bar }
The synthesis is a new target w for the old property items with a default value of 'Gorilla'.
let options = {
size: 100,
items: "Piggi"
}
let { title="Menu", items:w="Gorilla", size } = options;
let a = title;
let b = w;
console.log(a + " - " + b);
Solution- The problem is , we are overwriting the global object. it is why you have titile as Menu but option object does not have titile property. So, when you assign global object with option,
it still has items as "piggi"
plus you cannot assign object like this, you have to reassign each property in javascript.
i hope you got your answer.

What is `var { comma, separated, list } = name;` in JavaScript? [duplicate]

I haven't seen this syntax before and am wondering what it's all about.
var { Navigation } = require('react-router');
The brackets on the left are throwing a syntax error:
unexpected token {
I'm not sure what part of the webpack config is transforming or what the purpose of the syntax is. Is it a Harmony thing? Can someone enlighten me?
It's called destructuring assignment and it's part of the ES2015 standard.
The destructuring assignment syntax is a JavaScript expression that
makes it possible to extract data from arrays or objects using a
syntax that mirrors the construction of array and object literals.
Source: Destructuring assignment reference on MDN
Object destructuring
var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true
// Assign new variable names
var {p: foo, q: bar} = o;
console.log(foo); // 42
console.log(bar); // true
Array destructuring
var foo = ["one", "two", "three"];
// without destructuring
var one = foo[0];
var two = foo[1];
var three = foo[2];
// with destructuring
var [one, two, three] = foo;
This is destructuring assignment. It's a new feature of ECMAScript 2015.
var {
AppRegistry,
StyleSheet,
Text,
View,
} = React;
Is the equivalent to:
var AppRegistry = React.AppRegistry;
var StyleSheet = React.StyleSheet;
var Text = React.Text;
var View = React.View;
var { Navigation } = require('react-router');
... uses destructuring to achieve the same thing as ...
var Navigation = require('react-router').Navigation;
... but is far more readable.
It's a new feature in ES6 to destructure objects.
As we all know that there is an assignment operation taking place here, which means right side value is getting assigned to left side variable.
var { Navigation } = require('react-router');
In this case require('react-router') method returns an object with key-value pair, something like:
{ Navigation: function a(){},
Example1: function b(){},
Example2: function c(){}
}
And if we would like to take one key in that returned object say Navigation to a variable we can use Object destructuring for that.
This will only be possible only if we have the key in hand.
So after the assignment statement, local variable Navigation will contain function a(){}
Another example looks like this.
var { p, q } = { p: 1, q:2, r:3, s:4 };
console.log(p) //1;
console.log(q) //2;
instead of
const salary = personnel.salary
const sex = personnel.sex
const age = personnel.age
simply
const {salary, age, sex} = personnel

Javascript object bracket notation ({ Navigation } =) on left side of assign

I haven't seen this syntax before and am wondering what it's all about.
var { Navigation } = require('react-router');
The brackets on the left are throwing a syntax error:
unexpected token {
I'm not sure what part of the webpack config is transforming or what the purpose of the syntax is. Is it a Harmony thing? Can someone enlighten me?
It's called destructuring assignment and it's part of the ES2015 standard.
The destructuring assignment syntax is a JavaScript expression that
makes it possible to extract data from arrays or objects using a
syntax that mirrors the construction of array and object literals.
Source: Destructuring assignment reference on MDN
Object destructuring
var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true
// Assign new variable names
var {p: foo, q: bar} = o;
console.log(foo); // 42
console.log(bar); // true
Array destructuring
var foo = ["one", "two", "three"];
// without destructuring
var one = foo[0];
var two = foo[1];
var three = foo[2];
// with destructuring
var [one, two, three] = foo;
This is destructuring assignment. It's a new feature of ECMAScript 2015.
var {
AppRegistry,
StyleSheet,
Text,
View,
} = React;
Is the equivalent to:
var AppRegistry = React.AppRegistry;
var StyleSheet = React.StyleSheet;
var Text = React.Text;
var View = React.View;
var { Navigation } = require('react-router');
... uses destructuring to achieve the same thing as ...
var Navigation = require('react-router').Navigation;
... but is far more readable.
It's a new feature in ES6 to destructure objects.
As we all know that there is an assignment operation taking place here, which means right side value is getting assigned to left side variable.
var { Navigation } = require('react-router');
In this case require('react-router') method returns an object with key-value pair, something like:
{ Navigation: function a(){},
Example1: function b(){},
Example2: function c(){}
}
And if we would like to take one key in that returned object say Navigation to a variable we can use Object destructuring for that.
This will only be possible only if we have the key in hand.
So after the assignment statement, local variable Navigation will contain function a(){}
Another example looks like this.
var { p, q } = { p: 1, q:2, r:3, s:4 };
console.log(p) //1;
console.log(q) //2;
instead of
const salary = personnel.salary
const sex = personnel.sex
const age = personnel.age
simply
const {salary, age, sex} = personnel

Javascript: Server sided dynamic variable names

How would I create dynamic variable names in NodeJS? Some examples say to store in the window variable, but I was assuming that is client-side Javascript. Correct me if I'm wrong.
Generally you would do something like:
var myVariables = {};
var variableName = 'foo';
myVariables[variableName] = 42;
myVariables.foo // = 42
In node.js there is the global context, which is the equivalent of the window context in client-side js. Declaring a variable outside of any closure/function/module as you would in plain Javascript will make it reside in the global context, that is, as a property of global.
I understand from your question that you want something akin to the following:
var something = 42;
var varname = "something";
console.log(window[varname]);
This in node.js would become:
var something = 42;
var varname = "something";
console.log(global[varname]);
Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.
var type = 'article';
this[type+'_count'] = 1000; // in a function we use "this";
alert(article_count);
One possible solution may be:
Using REST parameter, one can create an array and add each dynamic variable (REST parameter item) as an object to that array.
// function for handling a dynamic list of variables using REST parameters
const dynamicVars = (...theArgs) => {
let tempDynamicVars = [];
// as long as there are arguments, a new object is added to the array dynamicVars, creating a dynamic object list of variables
for (let args = 0; args < theArgs.length; args++){
const vName = `v${args}`;
tempDynamicVars = [...tempDynamicVars, {[vName]: theArgs[args]}]; //using spread operator
// dynamicVars.push({[vName]: theArgs[args]}); // or using push - same output
}
return tempDynamicVars;
}
// short version from above
// const dynamicVars = (...theArgs) => theArgs.map((e, i) => ({[`v${i}`]: e}));
// checking
const first = dynamicVars("F", 321);
console.log("Dynamic variable array:", first);
console.log(` - ${first.length} dynamic variables`);
console.log(" - second variable in the list is:", first[1], "\n");
console.log(dynamicVars("x, y, z"));
console.log(dynamicVars(1, 2, 3));
console.log(dynamicVars("a", "b", "c", "d"));

Categories

Resources