Curly brackets (braces) in Node.js 'require' statement

Javascriptnode.jsEcmascript 6Destructuring

Javascript Problem Overview


I am trying to understand the difference between the two 'require' statements below.

Specifically, what is the purpose of the { }s wrapped around ipcMain?

const electron = require('electron')

const {ipcMain} = require('electron')

They both appear to assign the contents of the electron module, but they obviously function differently.

Can anyone shed some light?

Javascript Solutions


Solution 1 - Javascript

The second example uses destructuring.

This will call the specific variable (including functions) that are exported from the required module.

For example (functions.js):

module.exports = {
   func1,
   func2
}

is included in your file:

const { func1, func2 } = require('./functions')

Now you can call them individually,

func1()
func2()

as opposed to:

const Functions = require('./functions')

are called using dot notation:

Functions.func1()
Functions.func2()

Hope this helps.

You can read about destructuring here, it is a very useful part of ES6 and can be used with arrays as well as objects.

Solution 2 - Javascript

With const electron = require('electron'), the ipcMain module will be available as electron.ipcMain.

With const {ipcMain} = require('electron') the ipcMain module will be available as ipcMain.

This construct is called object destructuring and achieves the same as the Python construct

from library import ...

In its basic form it allows you to refer to the properties of an object directly:

var o = {prop1: '1', prop2: 2}
var {prop1, prop2} = o
console.log(prop1) // '1' (same as o.prop1)
console.log(prop2) // 2 (same as o.prop2)

Check:

const {ipcMain} = require('electron')
const myElectron = require('electron')
const myipcMain = myElectron.ipcMain
console.log(myipcMain===ipcMain) // true

You can use the destructuring assignment to import multiple properties of a JavaScript object, e.g.:

const { app, BrowserWindow, ipcMain } = require('electron')

If you use a property that doesn't exist, this will be set to undefined and you won't get an error.

const {app, BrowserWindow, ipcMain, doesntExist} = require('electron')
console.log(doesntExist) // undefined

See also: What does curly brackets in the var { … } = … statements do?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAproposArmadilloView Question on Stackoverflow
Solution 1 - JavascriptalexView Answer on Stackoverflow
Solution 2 - Javascriptuser2314737View Answer on Stackoverflow