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?

  • As per ecmascript-6 "let" is the good practice. – Mohamed Sameer Aug 14 '18 at 04:30
  • 1
    Possible duplicate of [What's the difference between using "let" and "var" to declare a variable in JavaScript?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable-in-jav) – connexo Aug 14 '18 at 04:34

2 Answers2

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 it case it isn't, the only way to make a true global scope variable is by direct assignment:

global.globalScopeVariable = 123;
Amadan
  • 191,408
  • 23
  • 240
  • 301
  • This will also do the same thing **globalScopeVariable = 123**; Please correct me if I am wrong. – Ammar Jan 28 '22 at 14:40
  • @Ammar Yes... unless you are in [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode). In strict mode, you will get an error. You should always `"use strict"`. – Amadan Jan 29 '22 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!
Aminu Kano
  • 2,595
  • 1
  • 24
  • 26
  • 3
    This is *not* true. Global variables defined with let and const do not become properties of the window object, unlike var variables. – user3700562 Jun 19 '20 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 Feb 17 '23 at 09:59