Skip to content

Latest commit

 

History

History
79 lines (59 loc) · 1.5 KB

block-scoped-var.md

File metadata and controls

79 lines (59 loc) · 1.5 KB

Treat var as Block Scoped (block-scoped-var)

The block-scoped-var rule generates warnings when variables are used outside of the block in which they were defined. This emulates C-style block scope.

Rule Details

This rule aims to reduce the usage of variables outside of their binding context and emulate traditional block scope from other languages. This is to help newcomers to the language avoid difficult bugs with variable hoisting.

Examples of incorrect code for this rule:

/*eslint block-scoped-var: "error"*/

function doIf() {
    if (true) {
        var build = true;
    }

    console.log(build);
}

function doIfElse() {
    if (true) {
        var build = true;
    } else {
        var build = false;
    }
}

function doTryCatch() {
    try {
        var build = 1;
    } catch (e) {
        var f = build;
    }
}

Examples of correct code for this rule:

/*eslint block-scoped-var: "error"*/

function doIf() {
    var build;

    if (true) {
        build = true;
    }

    console.log(build);
}

function doIfElse() {
    var build;

    if (true) {
        build = true;
    } else {
        build = false;
    }
}

function doTryCatch() {
    var build;
    var f;

    try {
        build = 1;
    } catch (e) {
        f = build;
    }
}

Further Reading