Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 443
AproposArmadillo Avatar asked Jul 29 '16 13:07

AproposArmadillo


People also ask

Are curly braces required around the statements in a function?

Yes, it works, but only up to a single line just after an 'if' or 'else' statement. If multiple lines are required to be used then curly braces are necessary.

What is curly braces in node JS?

In javascript code, curly brackets are used to deconstruct an object.

Are braces necessary in one line statements in javascript?

No, curly braces are not necessary, However, one very important reason to use the curly brace syntax is that, without it, there are several debuggers that will not stop on the line inside the if statement.

When should I use curly braces for es6 import?

The curly braces are used only for import when export is named. If the export is default then curly braces are not used for import.


1 Answers

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.

like image 79
alex Avatar answered Oct 19 '22 19:10

alex