undefinedfix
Sign in

JS function in the braces is what meaning, scope, how to explain it?

eeeeeen edited in Fri, 22 Apr 2022

Seeing that JS is written in this way, I don't know the meaning of this brace:

  function run(){
    {
      alert(1);
    }
 }

In fact, I don't quite understand that he just executed a method in braces. What does this writing have to do with the scope of variables.

6 Replies
3174N
commented on Sat, 23 Apr 2022

Code block has two different meanings

  • For the block level scope after ES6, many of the above answers have been mentioned
  • It is used for code segmentation and pure code maintenance requirements. For example, two things need to be done in a function, which have nothing to do with each other. In this way, they can be separated, or some of the code is not in the mainstream process. For example, you need to record a log and package it with {} to make the code easier to read. When combing the process, you don't need to care about this point It's a mission.{do something...}{do something...}do something...
David42
commented on Sat, 23 Apr 2022

The braces here belong to the block level scope in ES6

suxbr
commented on Sat, 23 Apr 2022

Let me talk about another case, such as rollup for Vue source code

if ('development' !== 'production') {
    alert(1)
}

After compilation:

{
    alert(1)
}
Mux
commented on Sat, 23 Apr 2022

ES6 adds a block level scope, and the variables in the block level scope cannot be accessed outside the block level scope. The VaR declarator does not recognize the block level scope, that is to say

{
    var a = 1;
}

It is not a block level scope, but let, const can identify the block level scope

rfqcw
commented on Sun, 24 Apr 2022

There are a lot of questions about the building owner, so I won't talk about them. Talk about what grammar means and how to explain it. Directly generate ast online and you will know everything. astexplorer

mhjld
commented on Sun, 24 Apr 2022

In ES6, you can think of braces as block level scopes,

lock This question has been locked and the reply function has been disabled.