01 New Variables - Gilian/001-ES6-By-Wes GitHub Wiki

01 - New Variables

The differences

  • var
    • reassignable
    • function-scoped
    • assigned to window if globally defined
    • leaking to window when used (for example) in a global if-clause
    • you can create two variables with the same name in the same scope
  • let
    • reassignable
    • block-scoped (includes functions)
    • perfect for for-loops, so i does not leak into the global scope
  • const
    • not reassignable
    • block-scoped (includes functions)
    • object attributes can be updated if the object is const but no reassignments

Rule of thumb
Use const for variables you do not want to alter, like selectors. Use let for everything else. Use var only if you define global scoped variables which need to change their value. Var is used to show that they are global scoped.

Concepts

  1. the temporal dead zone
    var variables are created (but not assigned a value) before all of the code runs. This causes a variable before it is assigned a value to be 'undefined' when accessed. This is not the case for let and const where there is an error if you try to access them before they are created. The space before the creation is called temporal dead zone