Search code examples
typescriptfunctionscopedeclaration

Trying to override a variable inside a function and get an error: "Block-scoped variable '...' used before its declaration.ts(2448)"


I'm writing a typescript function that accepts a numeric array (i.e., type: number[]) and calculates its mean. In addition, I want to account for when the input array might contain some null values. To this end, I added an argument, that when set to true, tells the function to remove nulls before calculating the mean.

But I can't figure out the proper way to do this, as I can't override the input within the function.

Here's my code for calcMean()

function calcMean(arr: number[], nullRemove: boolean = true): number {
    if (nullRemove) { // if TRUE, which is the default, then throw out nulls and re-assign to `arr`
        const arr: number[] = arr.filter((elem) => elem !== null);
    }
    // then simply calculate the mean of `arr`
    return arr.reduce((acc, v, i, a) => acc + v / a.length, 0); // https://stackoverflow.com/a/62372003/6105259
}

I then get an error:

Block-scoped variable 'arr' used before its declaration.ts(2448)

I also tried using let in addition or instead of const but it didn't solve the problem.

What am I missing here?


Solution

  • Two options for you:

    1. Don't redeclare it, just reassign it:

    function calcMean(arr: number[], nullRemove: boolean = true): number {
        if (nullRemove) { // if TRUE, which is the default, then throw out nulls and re-assign to `arr`
            arr = arr.filter((elem) => elem !== null);
            // ^^^ No `const` here
        }
        // then simply calculate the mean of `arr`
        return arr.reduce((acc, v, i, a) => acc + v / a.length, 0); // https://stackoverflow.com/a/62372003/6105259
    }
    

    Some folks believe reassigning parameters is poor style (I'm not one of them provided the function is quite small as in your case, but I understand the argument), so alternatively:

    2. Assign to a different variable:

    function calcMean(arr: number[], nullRemove: boolean = true): number {
        // Remove `null` if requested
        const a = nullRemove ? arr.filter(elem => elem !== null) : arr;
        // then simply calculate the mean of `arr`
        return a.reduce((acc, v, i, a) => acc + v / a.length, 0); // https://stackoverflow.com/a/62372003/6105259
    }