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
2 Answers
Reset to default 4In 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
版权声明:本文标题:javascript - Should you use 'var' or 'let' in the global scope? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744418862a2605335.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论