In ES6, I can achieve block scoping per case:
switch(somVar){
case 'first':
{
let itemId='foo';
}
break;
case 'second':
{
let itemId='bar';
}
}
Obviously, itemId
might as well be declared on top.
For my use case, locally scoped variables make more sense because in my overall code, it is more easily identifiable what's happening, and there are a number of case
's, whereas some blocks contain the variable in question and others don't.
I have't seen block scoping used for switch/case
as common usage.
My question is simply, whether there are reasons not to do it, stylistic-wise or else.
Edit, updated example code to avoid confusion:
const someFunc(action) => {
switch(action.type){
case 'first':
{
let itemId=action.someObj.someProp.id;
//Do something with itemId
}
break;
case 'second':
{
let itemId=action.someObj.someProp.id;
//Do something with itemId
}
break;
case 'third':
//No use of itemId
}
}
itemId could be declared at the top, but I'd prefer to look at the property per case. There doesn't appear to be an immediate reason to share the variable across different cases. It would also appear to be nonsense to 'invent' a different name for what is essentially the same.
This could probably be written differently, but this example is a common pattern in Flux architecture.
Abstract the logic into functions. Switch statements by themselves are difficult to read let alone a bunch of logic and variable scoping. It is much better to abstract the logic into functions. Also after abstracting to functions you will probably notice that there isn't much need for a switch statement all together. See Avoid use of switch statements section of the DockYard style guides.
function handleFirstCase() {
var itemId = 'foo';
// Do stuff with itemId
return expectedValue;
}
function handleSecondCase() {
var itemId = 'bar';
// Do stuff with itemId
return expectedValue;
}
let result;
switch(somVar){
case 'first':
result = handleFirstCase();
break;
case 'second':
result = handleSecondCase();
break;
}
Notice how the switch statement becomes one line. This can easily be distilled to a dictionary lookup instead:
const CASES = {
first() {
var itemId = 'foo';
// Do stuff with itemId
return expectedValue;
},
second() {
var itemId = 'bar';
// Do stuff with itemId
return expectedValue;
}
};
let result = CASES[someVar]();
The problem occures due to switch scenario is handled as a single block, irrespective of the individual case statments, as the 'break' statement is optional.
Rewriting your code to the following should do the job:
const someFunc(action) => {
if (action.type == 'first'){
let itemId=action.someObj.someProp.id;
//Do something with itemId
}
else if (action.type == 'second'){
let itemId=action.someObj.someProp.id;
//Do something with itemId
}
else { //Third
//No use of itemId
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With