Home > Blockchain >  Const Functions to an array from other file
Const Functions to an array from other file

Time:07-16

I have 2 functions to const in my index.js:

const funcE = require("../Functions/cmdError")
const funcH = require("../Functions/cmdHelp")

When I call functions must be like this:

funcE.cmdError(args)
funcH.cmdHelp(args)

I want join 2 const lines into 1 line and how to call these funtions?

CodePudding user response:

You have 3 possibilities to declare your constants in one line.

Option 1

The simplest way:

const funcE = require("../Functions/cmdError"); const funcH = require("../Functions/cmdHelp");

Option 2

Use a comma and don't use const for the second declaration.

const funcE = require("../Functions/cmdError"), funcH = require("../Functions/cmdHelp");

Option 3

Use Destructuring assignment.

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

const [funcE, funcH] = [require("../Functions/cmdError"), require("../Functions/cmdHelp")];

This is how you can invoke your functions in all cases:

funcE.cmdError(args)
funcH.cmdHelp(args)

This is what you can do, if you want to have 1 constant only:

const func = [require("../Functions/cmdError"), require("../Functions/cmdHelp")];

Invoke the functions with: func[0].cmdError(args) and func[1].cmdHelp(args)

OR

you could also declare an object.

const functions = {
  funcE: () => require("../Functions/cmdError"),
  funcH: () => require("../Functions/cmdHelp")
}

Invoke the functions with: functions.funcE() and functions.funcH()

CodePudding user response:

You can also reach your goal by doing this:

Create a new file, for example, index.js. In this index.js file write your "requires" and export them.

const funcE = require("../Functions/cmdError");
const funcH = require("../Functions/cmdHelp");

module.exports = {
  funcE,
  funcH
}

Then you can require the index.js file where you want and access these functions.

CodePudding user response:

I figured out how to do it already, thanks everyone.

const func = [require("../Functions/cmdHelp"), require("../Functions/cmdError")]

and call it:

func[0].cmdHelp(args)
func[1].cmdError(args)
  • Related