Home > Blockchain >  Redeclaring variables in switch case
Redeclaring variables in switch case

Time:10-19

const answers = random.int(1, 5)
 
const embed = new MessageEmbed()
   .setTitle('Bank Rob')
   .setColor('GREEN')
    
   switch(answers) {
     case 1:
       let description = `test 1`;
       break;
     case 2:
       let description = `test 2`
       break;
     case 3:
       let description = `test 3`
       break;
     case 4:
       let description = `test 4`
       break;
     case 5:
       let description = `test 5`
       break;
   }

embed.setDescription(description)

I'm trying to assign the variable description to be used outside of the switch case statement, I'm getting the error:

Cannot redeclare block-scoped variable "description"

CodePudding user response:

The easiest way to deal with this is to avoid the switch altogether: put the descriptions in an array and index it.

const DESCRIPTIONS = ['test 1', 'test 2', 'test 3', 'test 4', 'test 5'];
const answers = random.int(1, 5)
 
const embed = new MessageEmbed()
   .setTitle('Bank Rob')
   .setColor('GREEN')

embed.setDescription(DESCRIPTIONS[answers - 1]); // array is indexed from 0
  • Related