0

iam building a react-redux app in my reducer i got this error after compile my bundle.js with webpack using babel es2015 and stage-2, i did some research and it supose them the const scope are the block code, so why why iam getting an error of double declaration ? my reducer its like this function above

function print(foo){
  switch(foo){
    case 'test':
      const bar = 2;
      console.log(bar+1);
      break;
    case 'test1':
      const bar = 1;
      console.log(bar+2);
      break;
    default:
      console.log('no match')
      break;
  }
}
print('test');

1 Answers1

1

You need to wrap each case branch with curly braces like this:

function print(foo){
  switch(foo){
    case 'test': {
      const bar = 2;
      console.log(bar+1);
      break;
    }
    case 'test1': {
      const bar = 1;
      console.log(bar+2);
      break;
    }
  }
}

Everything within the switch statement is one block scope. The braces put each case within its own block scope -- without them, you're redeclaring a const within the same scope, which will error.

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183