asanas asanas - 1 month ago 15
Javascript Question

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?

Answer

if query_url can have multiple values depending on the switch branch obviously you need a variable ( declare either with var or let ).

const is set once and stays that way.

example usage with let

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