Post

Javascript var let const

Ref.: Var, Let, and Const – What’s the Difference?

var is globally scoped or function scoped.

var can be re-declared

Hoisting of var

They are all hoisted to the top of their scope.

1
2
console.log (greeter);
var greeter = "say hello"

interpreted as:

1
2
3
var greeter;
console.log (greeter);
greeter = "say hello"

var

1
2
3
4
5
6
7
8
var greeter = "hey hi";
var times = 4;

if (time > 3) {
  var greeter = "say Hello instead";
}

console.log(greeter); // "say Hello instead"

While this is not a problem if you knowingly want greeter to be redefined, it becomes a problem when you do not realize that a variable greeter has already been defined before.

let and const are block scoped

let can be updated but not re-declared

Hoisting of let

Unlike var initialized as undefined, the let keyword is not initialized. You’ll get a Reference Error before declaration.

const cannot be updated

This post is licensed under CC BY 4.0 by the author.