ES2015Variables / ES2015


let works just like var. In most cases, you can use let instead of var.

function greet (user) {
  let name =
  console.log('Hello, ' + name)

But what makes it different? Next

let vs. var

A let is only available inside the { ... } block they're in. In this example, the names are only available inside their respective if and else blocks.

Further reading...

Learn about let's cousin. Next


const is just like let, except you can't reassign it to a new value. Most guides now recommend using let and const instead of var.

Further reading...

What is block scoping? Next

Block scoping

let and const are said to be block scoping. In JavaScript, a block is code inside { and }. These variables are only available inside their blocks.

Block scoping affects other kinds of blocks.

function greet () {  }
if (hidden) {  }
else {  }
try {  }
catch (e) {  }
finally {  }
switch (state) {  }
for (;;) {  }
while (true) {  }
Further reading...

What about blocks inside blocks? Next

Nested blocks

Variables defined using let and const are available only inside {...} blocks, and other blocks inside them.

function run (user) {
  if (user) {
    let running = user.state === 'running'
    if (running) {
      running is still available here
    } else {
      and here, too
  } else {
    but not here!

Learn recap what we've learned. Next


let is the new var. const is the same, but doesn't let you change it.

let a = 'hello'
const b = 'hi'

They are block scoping: they are only available within {...} blocks, but not outside them.

if (true) {
  let a = 'hello'
console.log(a)  undefined

Learn what's new with objects. Next chapter