It is not recommended to declare variables or functions inside {} code blocks (strict mode)

How to understand ESLint's no-inner-declarations rule?

Description of the problem: The project uses eslint to detect the standardization of the code. When compiling the code, commit reports an error ( Move function declaration to function body root (no-inner-declarations) at xxxx )

code show as below:

//解析:在处理场景中是在条件满足的时候才会执行函数中的代码,
if (true) {
    // 在某个条件分支下创建一个函数,并且只在这个分支内使用。
    function a() {
        // code...
    }
    a();
}
// 报错:
"Move function declaration to program root. (no-inner-declarations)"

Before ES6, function declarations could only be at the top of the program or another function body, so it was wrong to declare a functional error inside a code block. In addition, in JavaScript, the declaration of the code will be promoted to the top of the current scope of the code , so it is also unwise to declare variables inside code blocks.

Record: Under normal circumstances, it does not matter where the function is declared (it is also possible inside the conditional branch), but in strict mode, an error will be reported to indicate that such writing is not standardized. If it is inside the condition of the loop, then this function If it is declared multiple times, memory resources are wasted, and if it is only declared inside the conditional branch, it is not conducive to code reuse, ensuring the standardization of the code format when implementing logic.

This error occurred during the operation, I searched for information and saw everyone’s explanations, and sorted out the records for learning according to my own understanding

Guess you like

Origin blog.csdn.net/weixin_45634433/article/details/119006731