What is the Point of Var in Modern JavaScript
With let having been standard in JavaScript for awhile now in all modern browsers, it is questionable why var is still needed. Even for older environments a transpiler like Babel can be used to convert newer syntax JS into older JS syntax automatically dealing with any let and const support issues.
It turns out there are still a few rare use cases where var is useful. Firstly, it is important to contrast its behavior with let:
let can only be used for a declaration once in a function (or related) scope
let is block scoped rather than function scoped
This illustrates the implications of the above:
function exampleTests() { var a = true; let b = 'value1'; if (a) { let c = 1; var d = 2; } if (typeof c !== 'undefined') { console.log('let c: ', c); } if (typeof d !== 'undefined') { console.log('var d: ', d); var a = false; // Does not affect the parent block let (use b = 'value2' instead) let b = 'value2'; } // Will throw a declaration error // let b = 'value3'; console.log('var a: ', a); console.log('let b: ', b); } exampleTests(); // var d: 2 // var a: false // let b: value1
As you can see let prevents a lot of common errors and confusion where var is used. There are even more cases - the above are just the most common. So why use var at all? One case is when you need to optionally import into a global (browser) or file level (Node.js) variable where code needs to run in a brower and Node.js without maintaining 2 separate versions. In general, libraries are imported via require and not globally in Node.js. But in browsers, especially in older environments without bundlers like Webpack, libraries are often instantiated globally:
// Assume all non-Node.js environments (that do not have require) are browser ones if (typeof require !== 'undefined') { var _ = require('lodash'); } console.log('Lodash version:', _.VERSION); // Lodash version: 4.17.10 (On a browser this may vary)
At first glance, you may think to just declare let at the top and assign:
let _; if (typeof require !== 'undefined') { _ = require('lodash'); } console.log('Lodash version:', _.VERSION);
Though you will get something like Uncaught TypeError: Cannot read property 'VERSION' of undefined. This is because by declaring _, you set the original _ reference to nothing. Combined with let being scoped to the block inside the if, means that a keyword which allows itself to be redeclared and affect the function scope rather than block scope is necessary.
I need to emphasize that even though var has more flexibility than let, let should be used whenever var is not absolutely required. It is almost always better to use a simpler, less flexible, way of doing something then move to the more complex way rather than the other way around. The less flexible a concept is, the less ways it can go wrong.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2019/varUsage.js












