how to understand this JavaScript code output? [duplicate] - javascript

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

Related

javascript functional programming External Dependence mutation

Can someone explain this javascript behavior?
let a = {z: true};
console.log(a);
const modify = obj => {
let b = {
a: "hello",
b: 22
}
obj = {...obj, ...b}
return obj;
}
modify(a);
console.log(modify(a))
output:
{
z:true,
a:"hello",
b:22
}
is obj in obj = {...obj, ...b} an implicitly new created object or is this the same obj parameter of modify.
because when I try to comment the return obj; line (//return obj;) in a visual studio text editor the parameter obj inside the modify function seems to be faded meaning that I'm not using it inside the function. Also without having to return obj; i just wanted to alter a given object and bind to it some new properties. is this possible?
The object in your code is not mutated. The object literal notation (with { }) always creates an object. Secondly, the assignment to obj is to the local variable with that name, not the variable of the caller (a). To mutate the given object, you can use Object.assign:
let a = {z: true};
console.log(a);
const modify = obj => {
let b = {
a: "hello",
b: 22
}
// The return is not absolutely necessary...
return Object.assign(obj, b);
}
modify(a);
console.log(a);
Of course, when you let functions mutate objects, you are no longer in line with functional programming principles.
obj = {...obj, ...b} will create a new object.
If you want to change the given object just change his properties:
const modify = obj => {
obj.a = "hello"
obj.b = 22
}
If you want to combine new object to your existsing object you can also use Object.assign:
Object.assign(obj, b)

using optional chaining in array of object and destructing

I have an object like this
const obj = [{a: 'a'}];
I can get it like:
const { a } = obj[0]; //a
but what if obj['x'] doesn't exist?
I tried this with optional chainning but doesn't seem to work.
const { a } = obj?.[1];
You are close to it. You should make sure to fallback with an empty object, for the destructing later to make sense
const obj = [{a: 'a'}];
const { a } = obj?.[1] || {};
console.log(a)
Update
This would be even shorter if you don't use destructing in this case
const obj = [{a: 'a'}];
const a = obj?.[1]?.a; // or: obj?.[1]?.['a']
console.log(a)
You can use the Logical OR operator.
const { a } = obj[x] || {}
If obj does not have a property x, a will be set to undefined.
You could festructure with an index as computed property and a default object for a missing item of the array.
const
obj = [{ a: 'a' }],
{ [2]: { a } = {} } = obj;
console.log(a);
Take a look at the following three cases, where I've used optional chaining.
You need to first check if the first element of the array (index 0) exists and then check if there's a field a in it.
// Case 1:
const obj1 = [{ a: "a" }];
console.log(obj1?.[0]?.a); // "a"
// Case 2:
const obj2 = [{ b: "b" }];
console.log(obj2?.[0]?.a); // undefined
// Case 3:
const obj3 = [];
console.log(obj3?.[0]?.a); // undefined

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

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

Categories

Resources