Comment on page
Difference Between let and var
What's the difference between using
let
and var
in JavaScript?var
- variables are scoped to the function body.let
- variables are scoped to the immediate enclosing block denoted by{}
.
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();
In strict mode,
var
can be redeclared, while let
will raise a SyntaxError
.'use strict';
var foo = "foo1";
var foo = "foo2"; // 'foo1' is replaced with 'foo2'.
let bar = "bar1";
let bar = "bar2"; // SyntaxError: Identifier 'bar' has already been declared
var
- hoisted and initialized. Meaning they are accessible in their enclosing scope even before they are declared. Their value isundefined
.let
- hoisted but not initialized until their definition is evaluated. Accessing them before the initialization results in aReferenceError
.
function varHoisting() {
console.log(foo); // undefined
var foo = "Foo";
console.log(foo); // Foo
}
function letHoisting() {
console.log(foo); // ReferenceError
let foo = "Foo";
console.log(foo); // Foo
}
var
- will create a property on the global object.let
- will not create a property on the global object.
var foo = "Foo"; // globally scoped
let bar = "Bar"; // globally scoped but not part of the global object
// in the browser
console.log(window.foo); // Foo
console.log(window.bar); // undefined
// in nodejs
console.log(this.foo); // Foo
console.log(this.bar); // undefined
Last modified 1mo ago