admin管理员组

文章数量:1403452

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?

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?

Share Improve this question asked Aug 14, 2018 at 4:27 user6369603user6369603 2
  • As per ecmascript-6 "let" is the good practice. – Sameer Commented Aug 14, 2018 at 4:30
  • 1 Possible duplicate of What's the difference between using "let" and "var" to declare a variable in JavaScript? – connexo Commented Aug 14, 2018 at 4:34
Add a ment  | 

2 Answers 2

Reset to default 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;

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!

本文标签: javascriptShould you use 39var39 or 39let39 in the global scopeStack Overflow