8

Let's say I have this express application and want to add a global variable at the top

import express from 'express';

const app = express();

// var globalScopeVariable = 123;

app.get('/', (req, res) => {
  // home page
});

app.get('/create/:message', (req, res) => {
  //  add block
});

app.get('/add/:peerPort', (req, res) => {
  // add peer
});

Would it be good practice to use 'var' or 'let' in this scenario?

2

2 Answers 2

4

In your case (Node.js), neither var nor let make a global scope variable; both will create a module-scope variable (accessible inside this module, but not in other modules). This may be what you want (in which case, let is generally preferred these days, and var should be consigned to history); but in case it isn't, the only way to make a true global scope variable is by direct assignment:

global.globalScopeVariable = 123;
2
  • This will also do the same thing globalScopeVariable = 123; Please correct me if I am wrong.
    – Ammar
    Commented Jan 28, 2022 at 14:40
  • 1
    @Ammar Yes... unless you are in strict mode. In strict mode, you will get an error. You should always "use strict".
    – Amadan
    Commented Jan 29, 2022 at 15:13
2

If your variable can be reassigned, then use let otherwise use const. You don't have to bother about var anymore.

You can always consider the following powerful master rules around variable declaration in modern JavaScript.

  • Stop using var as soon as you can!
  • Use const whenever you can!
  • Use let only when you really have to!
2
  • 3
    This is not true. Global variables defined with let and const do not become properties of the window object, unlike var variables. Commented Jun 19, 2020 at 22:26
  • I'm glad someone pointed this FACT out, as it seems much is maligned by opinion or what might be seen in code snippets/examples [or via hand me down knowledge etc] on this subject. Anyway well done I say, this is actually the only production-level knowledge response to the OPs question here :)
    – gruffy321
    Commented Feb 17, 2023 at 9:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.