DEV Community

Seonyoung Chloe (she/they)
Seonyoung Chloe (she/they)

Posted on

68 : How does let use in javascript and Why

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. ... When used inside a block, let limits the variable's scope to that block. Note the difference between var whose scope is inside the function where it is declared.

The reason why let keyword was introduced to the language was functioned scope is confusing and was one of the main sources of bugs in JavaScript.

let can also be used to avoid problems with closures. It binds fresh value rather than keeping an old reference as shown in the examples below.

  • A variable defined using a var statement is known throughout the function it is defined in, from the start of the function. (*)
  • A variable defined using a let statement is only known in the block it is defined in, from the moment it is defined onward. (**)

Reference

Top comments (0)