3
votes

I am using ESLint to check my javascript code on build and I am getting a no-unused-vars error followed by a no-undef error for the same variable. I can't undertand how the variable can be both unused and undefined.

export function count(){
    if (counter > 3){
        const a = 'big';
    } else {
        const a = 'small';
    }
    return a;
}

Given the pseudode representation above I get the following errors from ESLint:

line 3 error  'a' is defined but never used  no-unused-vars
line 5 error  'a' is defined but never used  no-unused-vars
line 7 error  'a' is not defined             no-undef

Any ideas on how to get round this?

3

3 Answers

5
votes

const is block-scoped. So what you're doing there is creating an a within whichever block gets executed, not using it, letting it go out of scope, and then trying to return a different a that the function closes over (which will cause a ReferenceError if there is no a being closed over). The return a; line doesn't refer to the a declared within either of the blocks above it; that one has gone out of scope by then.

So instead:

export function count(){
    const a = counter > 3 ? 'big' : 'small';
    return a;
}

or

export function count(){
    let a; // Declared outside the blocks
    if (counter > 3){
        a = 'big';
    } else {
        a = 'small';
    }
    return a;
}
1
votes

You define your const inside the if, it is not living in the function scope.

you need to define it like

 export function count(){
    let a;
    if (counter > 3){
        a = 'big';
    } else {
        a = 'small';
    }
    return a;
}

More info, read next chapters of https://github.com/getify/You-Dont-Know-JS/tree/master/scope%20%26%20closures

0
votes

Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can't be redeclared.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const