Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
308 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...