Home > OS >  Cannot redeclare block-scoped variable, even though they are inside different cases
Cannot redeclare block-scoped variable, even though they are inside different cases

Time:06-29

Inside a controller method I have the code block below. Visual Studio Code gives the error:

Cannot redeclare block-scoped variable 'count' and 'rows'

But I don't understand this because these variables are declared inside different cases and only 1 case will fire. How should I handle this?

switch (tab) {
    case "active":
        const { count, rows } = await User.findAndCountAll({
            where: {
                ...query,
            },
            offset,
            limit,
        });

        break;

    case "favourites":
        const { count, rows } = await User.findAndCountAll({
            where: {
                ...query,
                [Op.or]: [{ name: {[Op.like]: `%${searchText}%` }}],
            },
            offset,
            limit,
        });
        ...

CodePudding user response:

The switch statement doesn't have different scopes by default, in fact if you don't use the break keyword at the end of a case the script will execute all the code in all the cases until it finds a break or the switch statement ends.

For example:

switch(1) {
    case 1:
        console.log('case 1');
    case 2:
        console.log('case 2');
}
// OUTPUT:
// case 1
// case 2

In this case all the cases were executed because i haven't used any break.

The only scope in a switch is the switch itself so how can you achieve your goal?

You can do it by wrapping your cases inside brackets, so it will become:

switch(1) {
    case 1: {
        const n = 1
        console.log('case '   n)
        break
    }
    case 2: {
        const n = 2
        console.log('case '   n)
        break
    }
}
// That's valid

If you don't want to duplicate your code just to edit the query you would probably do something like:

const query = { /* whatever */ }

const { count, rows } = await User.findAndCountAll({
    where: tab === 'active' ? {
        ...query,
    } : {
        ...query,
        [Op.or]: [{ name: {[Op.like]: `%${searchText}%` }}]
    },
    offset,
    limit,
})

By using ternary operator you don't even have to implement a switch and duplicate your code, you just change the query part based on your variable

  • Related