Block scoping questions in JavaScript

Question:

The doubts are as follows:

  • What is the difference between block scope and function scope in JavaScript?
  • The idea of ​​block scope came about in EcmaScript 6 with let and const ?

Answer:

What is the difference between block scope and function scope in JavaScript?

As of ES6, using let or const it is possible to declare variables that only exist inside {} blocks.

The most common example is inside if , for , try , catch but also simply:

 const foo = 123; { // console.log(foo); // Erro, detecta a variável mas ainda não está declarada const foo = 456; console.log(foo); // 456 } console.log(foo); // 123

In JavaScript prior to ES6 there was only var which is not block scope sensitive and only respects function scope. let and const respect function and block scope.

Synthesizing:

╔═════════════════════════╦════════════╦═════════════╦═════════════╗
║                         ║   var      ║    let      ║    const    ║
╠═════════════════════════╬════════════╬═════════════╬═════════════╣
║ pode ser sobre-escrita  ║     ✓      ║      ✓      ║      x      ║
╠═════════════════════════╬════════════╬═════════════╬═════════════╣
║ escopo                  ║   funcão   ║    bloco    ║    bloco    ║
╠═════════════════════════╬════════════╬═════════════╬═════════════╣
║ referenciável antes da  ║            ║             ║             ║
║ linha de declaração     ║     ✓      ║      x      ║      x      ║
╚═════════════════════════╩════════════╩═════════════╩═════════════╝

The idea of ​​block scope came about in EcmaScript 6 with let and const?

Yes, before there was only "function scope"

Scroll to Top