最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Should you use 'var' or 'let' in the global scope? - Stack Overflow

programmeradmin5浏览0评论

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!
发布评论

评论列表(0)

  1. 暂无评论