0

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 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:


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí