EN
Node.js - global variables
0 points
In this article, we would like to show you how to declare and use global variables in Node.js.
Quick solution:
xxxxxxxxxx
1
global.globalVariable = 'Global variable value.';
2
console.log(globalVariable); // output: 'Global variable value.'
Global variables such as regular variables can be initialized with a value, changed, and even cleared out.
The only difference between a global variable and a regular variable is their scope.
In this example, we create global variable inside example.js file. We can also use and modify it in index.js file.
index.js
xxxxxxxxxx
1
require('./example.js');
2
3
console.log(globalVariable); // output: undefined
4
5
globalVariable = 'Value changed in index.js.';
6
console.log(globalVariable); // output: 'Value changed in index.js.'
example.js
xxxxxxxxxx
1
global.globalVariable = 'Example value initialized in example.js';
2
console.log(globalVariable); // output: 'Example value initialized in example.js'
3
4
globalVariable = 'Value changed in example.js';
5
console.log(globalVariable); // output: 'Value changed in example.js'
6
7
globalVariable = undefined;
8
console.log(globalVariable); // output: undefined
Run the application :
xxxxxxxxxx
1
node index.js
Output:
xxxxxxxxxx
1
Example value initialized in example.js
2
Value changed in example.js
3
undefined
4
undefined
5
Value changed in index.js.