InspectorDanno
InspectorDanno

Reputation: 995

Const instead of var for function-scoped variables?

I've been reading about the Principle of Least Privilege and am confused when to use let vs. var vs. const, specifically in function-level scope.

I read that:

Use let in places you know you need block scoping, and you've specifically thought about those implications. But continue to use var for variables that either cannot easily be block scoped, or which shouldn't be block scoped. There are going to be places in real world code where some variables are going to be properly scoped to the entire function, and for those variables, var is a better signal.

Can const be used of var for function-scoped variables? For example:

function foo() {
    const a = 10;

    if (a > 2) {
        let b = a * 3;
        console.log(b);
    }

    if (a > 5) {
        let c = a / 2;
        console.log(c);
    }

    console.log(a);
}

Instead of:

function foo() {
    var a = 10;

    if (a > 2) {
        let b = a * 3;
        console.log(b);
    }

    if (a > 5) {
        let c = a / 2;
        console.log(c);
    }

    console.log(a);
}

Upvotes: 0

Views: 67

Answers (1)

AndrewL64
AndrewL64

Reputation: 16301

For the above code, const should be used instead of var or let because you are using the variable a for outputting new variables (b & c) and not manipulating or changing the variable a itself. So in other words, the value 'a' remains constant throughout the condition statements.

  • Const: Use const if you don't have to change the value of a variable at all.
  • Let: Use 'let' if you have to change the value of a variable later.
  • Var: Avoid using var since 'let' has an important scoping mechanism that 'var' doesn't have called block-scoping.

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

Via - Mozilla Docs

Upvotes: 1

Related Questions