Questions about block scope in Javascript

Asked

Viewed 449 times

5

The doubts are as follows:

  • What is the difference between block scope and function scope in Javascript?
  • The idea of block scope arose in Ecmascript 6 with let and const?

2 answers

8


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

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

The most common example is within 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 before ES6 only existed var which is not sensitive to the scope of blocks and only respects the scope of functions. let and const respect the 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 arose in Ecmascript 6 with Let and const?

Yes, before there was only "Function Scope"

2

A block scope is that within blocks of code for, if else, try catch among others:

let foo = undefined;

try {
    let foo = 'foo';

    throw new Error();
} catch(e) {
    //foo === undefined
    console.log(foo);
} finally {
    //foo === undefined
    console.log(foo);
}

if (true) {
    let foo = 'foo';
}

//foo === undefined
console.log(foo);

The variables let foo = 'foo'; only exist within the respective blocks (try and if), in the blocks catch, finally and in the global scope the variable foo refers to the variable in the global scope let foo = undefined;

The function scope is equal, but instead of any code block, it is the block of a function:

let foo = undefined;

function bar() {
    var foo = 'foo';
}
bar();

//foo === undefined
console.log(foo);

const baz = () => {
    var foo = 'foo';
}
baz();

//foo === undefined
console.log(foo);

class Qux {
    constructor() {
        var foo = 'foo';
    }
}
new Qux();

//foo === undefined
console.log(foo);

As you can see all variables var foo = 'foo'; do not exist outside the function, both traditional and Arrow functions, or class as in the previous examples in relation to the block scope

I can’t tell if this kind of scope came up with ES6, but before it was not possible, at least not with Javascript, maybe something with Typescript, Coffescript or something like that

Browser other questions tagged

You are not signed in. Login or sign up in order to post.