Languages

Node.js - require() without assigning it to variable

0 points
Asked by:
Vanessa-Drake
418

Can I use the require() without assigning it into a variable?

1 answer
0 points
Answered by:
Vanessa-Drake
418

Technically yes, because require() only executes code written in the module.

The code may return something or not. When it doesn't matter if the code returns anything and you want to execute the code only once you can use the require() without assigning it to a variable.

Note:

Even if you require() that module multiple times the code would execute only once.

Practical example

example.js:

console.log('Hello from example.js');

index.js:

require('./example.js');
console.log('Hello from index.js');

Now, when you run the node index.js command, you will get the following output:

Hello from example.js
Hello from index.js 
0 comments Add comment
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join