Photo by Pakata Goh on Unsplash
JavaScript is a powerful language because you can write an entire software without adopting any other programming language at all.
var
used to be a way to declare variables in JavaScript. However, declaring a variable or object in this way is now very rare due to the nightmare it can create in your JavaScript project.
var obj = {}
// instead let (or const) is used to declare a variable
Starting with ECMAScript 6, the let
statement was introduced.
Here then is a brief overview of why var
is no longer or rarely used in JavaScript projects for declaring variables.
Note: If you’re already familiar with the pitfalls of using var, this article may still serve as a nice refresher for you.
1. Scoping — the main reason to avoid var
Scoping is the key difference between var and let.
var
variables are scoped to the immediate function body (hence the function scope) while let
variables are scoped to the immediate enclosing block denoted by { }
.
Let’s understand what that means via code.
function run() {
var foo = "Foo";
let bar = "Bar";
console.log(foo, bar); // Foo Bar{
var moo = "Mooo";
let baz = "Bazz";
console.log(moo, baz); // Mooo Bazz
}
console.log(moo); // Mooo
console.log(baz); // ReferenceError}run();
The reason why the let
keyword was introduced to the language was function scope is confusing and was one of the main sources of bugs in JavaScript.
2. Hoisting — not a worry for let
First, we need to go over what hoisting is. Variables are accessible in their enclosing scope even before they are declared.
function run() {
console.log(foo); // undefined
// Hoisting in action !
var foo = "Foo";
console.log(foo); // Foo
}
run();
But no worries! Let
won't let that happen.
function checkHoisting() {
console.log(foo); // ReferenceError
let foo = "Foo";
console.log(foo); // Foo
}
checkHoisting();
3. Global Object Binding
At the top level, let
, unlike var
, does not create a property on the global object.
var foo = "Foo"; // globally scoped
let bar = "Bar"; // not allowed to be globally scoped
console.log(window.foo); // Foo
console.log(window.bar); // undefined
4. Redeclaration. Not Good with Let
In strict mode, var
will let you re-declare the same variable in the same scope while let
raises a SyntaxError.
"use strict";
var foo = "foo1";
var foo = "foo2"; // No problem, 'foo1' is replaced with 'foo2'.
let bar = "bar1";
let bar = "bar2"; // SyntaxError: Identifier 'bar' has already been declared
Check out the actual StackOverflow thread for more or write in the comments if you think I missed anything. I will add that and update the article accordingly. Happy reading!