Understanding var, let and const with Examples

Var

Scope

var a = 2; // globally scoped variablefunction foo() {
console.log(a);
}
foo(); // prints out 2console.log(window.a); // prints out 2
var a = 2; // globally scoped variablewindow.b = 3; // new property of window object, also globally scopeddelete a; // returns falsedelete b; // returns true
function bar() {
var a = 2; // only available inside this function
console.log(a);
}
bar(); // prints out 2console.log(a); // Uncaught ReferenceError: a is not definedconsole.log(window.a); // prints out undefined
function foo() {
a = 2; // note there is no var in front of the variable name
console.log(a);
}
foo(); // prints out 2console.log(a); // prints out 2console.log(window.a); // prints out 2
var a = 2;function foo() {
a = 3; // the value of the global variable a is overwritten here
console.log(a);
}
console.log(a); // prints out 2foo(); // prints out 3console.log(a); // prints out 3, the old value got overwritten

Hoisting

console.log(a); // prints out undefined. This doesn't mean the variable a is not defined. It means the value of a is undefineda = 2;console.log(a); // prints out 2 as we just assigned a value to itvar a;

Let

Scope

{ // note the curly bracket here
let a = 2;
console.log(a); // prints out 2
}
console.log(a); // Uncaught ReferenceError: a is not defined
let a = 2;function foo() {
console.log(a);
}
foo(); // prints out 2console.log(a); // prints out 2console.log(window.a); // prints out undefined
let a = 2; // declare for the first time, no problemlet a = 2; // Uncaught SyntaxError: redeclaration of let a

Hoisting

function foo() {
console.log(a);
let a;
}
foo(); // Uncaught ReferenceError: Cannot access 'a' before initializationfunction bar() {
let b;
console.log(b);
}
bar(); // prints undefined

Const

{
const a = 2;
a = 3; // Uncaught TypeError: Assignment to constant variable.
}
{
const a = {};
a.foo = "hello";
a.bar = "world";
console.log(a.foo); // prints out hello
console.log(a.bar); // prints out world
}

Scope

{
const a = 2;
console.log(a); // prints out 2
}
console.log(a); // Uncaught ReferenceError: a is not defined

Hoisting

--

--

A lifelong learner who has enthusiasm for sharing knowledge; a developer who loves bringing ideas to life.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Wenhe Qi

A lifelong learner who has enthusiasm for sharing knowledge; a developer who loves bringing ideas to life.