Skip to main content

var vs let vs const

ES2015 (or ES6) introduced two new ways to create variables, let and const.

var​

  1. var is function scoped
  2. This will give undefined when accessing a variable before it's declared
  3. it creates a global property on window with the same name.
  4. is reassignable.
  5. is redeclarable.

Ex: var <<variable_name>>;

Example:
--------

var city = "Coral Springs";

console.log(window.city);
Example2:
--------

var city = "Florence";

function bubble() {
var city = "Siena";
console.log(city);
}

bubble(); // "Siena"

console.log(city); // "Florence"

let​

  1. let is block scoped.
  2. ReferenceError when accessing a variable before it's declared
  3. it does not create any global property on window.
  4. is reassignable.
  5. is not redeclarable.

Ex: let <<variable_name>>;

What that means is that a variable created with the let keyword is available inside the “block” that it was created in as well as any nested blocks. When I say “block”, I mean anything surrounded by a curly brace like in a for loop or an if statement.

const​

const is almost exactly the same as let. However, the only difference is that once you’ve assigned a value to a variable using const, you can’t reassign it to a new value.

  1. block scoped
  2. ReferenceError when accessing a variable before it's declared
  3. it does not create any global property on window.
  4. is not reassignable.
  5. is not redeclarable.

Ex: const handle = 'test';

tip

The take away above is that variables declared with let can be re-assigned, but variables declared with const can’t be.