12/08/2018, 17:10

What are the differences between variables created using let, var or const?

Scope var If a variable is created inside a function, it is scoped to the function If a variable is created outside of any function, it is scoped to the global object let & const let and const are block scoped let and const are only accessible within ...

Scope

var

  • If a variable is created inside a function, it is scoped to the function
  • If a variable is created outside of any function, it is scoped to the global object

let & const

  • let and const are block scoped
  • let and const are only accessible within the nearest set of curly braces (function, if-else block, or for-loop)

Hoisting

  • Javascirpt hoisting: move all declarations to the top of the current scope (current script/current function), so a variable can be used before it has been declared.
  • var allows variables to be hoisted
  • let and const will NOT allow hoisted

Redeclaring

  • redeclaring a variable with var will NOT throw an error
  • redeclaring a variable with let or const will throw an error

Reasigning

  • let allows assigning the variable's value
  • const does NOT allow assigning the variable's value

ref:

  • https://www.w3schools.com/js/js_hoisting.asp
  • https://github.com/yangshun/front-end-interview-handbook/blob/master/questions/javascript-questions.md#what-are-the-differences-between-variables-created-using-let-var-or-const
0