What is `var { comma, separated, list } = name;` in JavaScript? [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

What does the syntax let = { as:comp, ...props } = props; mean? [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

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

Javascript: How to create an object from a dot separated string?

I ran into this potential scenario that I posed to a few of my employees as a test question. I can think of a couple ways to solve this problem, but neither of them are very pretty. I was wondering what solutions might be best for this as well as any optimization tips. Here's the question:
Given some arbitrary string "mystr" in dot notation (e.g. mystr = "node1.node2.node3.node4") at any length, write a function called "expand" that will create each of these items as a new node layer in a js object. For the example above, it should output the following, given that my object name is "blah":
blah: { node1: { node2: { node3: { node4: {}}}}}
From the function call:
mystr = "node1.node2.node3.node4";
blah = {};
expand(blah,mystr);
Alternately, if easier, the function could be created to set a variable as a returned value:
mystr = "node1.node2.node3.node4";
blah = expand(mystr);
Extra credit: have an optional function parameter that will set the value of the last node. So, if I called my function "expand" and called it like so: expand(blah, mystr, "value"), the output should give the same as before but with node4 = "value" instead of {}.
In ES6 you can do it like this:
const expand = (str, defaultVal = {}) => {
return str.split('.').reduceRight((acc, currentVal) => {
return {
[currentVal]: acc
}
}, defaultVal)
}
const blah = expand('a.b.c.d', 'last value')
console.log(blah)
Here's a method that popped up in my mind. It splits the string on the dot notation, and then loops through the nodes to create objects inside of objects, using a 'shifting reference' (not sure if that's the right term though).
The object output within the function contains the full object being built throughout the function, but ref keeps a reference that shifts to deeper and deeper within output, as new sub-objects are created in the for-loop.
Finally, the last value is applied to the last given name.
function expand(str, value)
{
var items = mystr.split(".") // split on dot notation
var output = {} // prepare an empty object, to fill later
var ref = output // keep a reference of the new object
// loop through all nodes, except the last one
for(var i = 0; i < items.length - 1; i ++)
{
ref[items[i]] = {} // create a new element inside the reference
ref = ref[items[i]] // shift the reference to the newly created object
}
ref[items[items.length - 1]] = value // apply the final value
return output // return the full object
}
The object is then returned, so this notation can be used:
mystr = "node1.node2.node3.node4";
blah = expand(mystr, "lastvalue");
var obj = {a:{b:{c:"a"}}};
const path = "a.b.c".split(".");
while(path.length > 1){
obj = obj[path.shift()];
}
obj[path.shift()] = "a";

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