Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Duplicate Const Declaration in Switch Case Statement

I have the following code and I get the error 'Duplicate Declaration query_url'.

  switch(condition) {
    case 'complex':
      const query_url = `something`;
      break;
    default:
      const query_url = `something`;
      break;
  }

I understand that query_url is getting declared twice which isn't right. But i don't know how to resolve this. Can someone please help on what should be the correct way to make this work?

like image 784
asanas Avatar asked Mar 02 '16 11:03

asanas


2 Answers

Try wrapping the cases in blocks:

switch(condition) {
  case 'complex': {
    const query_url = `something`;
    … // do something
    break;
  }
  default: {
    const query_url = `something`;
    … // do something else
    break;
  }
}
like image 108
Bergi Avatar answered Oct 19 '22 11:10

Bergi


I personally prefer (and tend to abuse) the following in these sorts of cases:

const query_url = (()=>
{
     switch(condition)
           case 'complex': return 'something';
           default       : return 'something-else';
})();

(this requires ES6 or declaring "use-strict" in Node 4.x though)

Update: Alternatively, much more compact depending on if there is any logic there or if it's a simple assignment:

const query_url = {complex : 'something'}[condition] || 'something-else';

Also, of course, depends on the amount of outside-logic embedded in those switch statements!

like image 17
rob2d Avatar answered Oct 19 '22 10:10

rob2d