javascript - ES6 block scoping with in switch -


in es6, can achieve block scoping per case:

switch(somvar){     case 'first':      {         let itemid='foo';      }     break;      case 'second':      {          let itemid='bar';      }  }  

obviously, itemid might declared on top.
use case, locally scoped variables make more sense because in overall code, more identifiable what's happening, , there number of case's, whereas blocks contain variable in question , others don't.

i have't seen block scoping used switch/case common usage.
question simply, whether there reasons not it, stylistic-wise or else.

edit, updated example code avoid confusion:

const somefunc(action) => {      switch(action.type){          case 'first':          {              let itemid=action.someobj.someprop.id;              //do itemid         }          break;          case 'second':          {              let itemid=action.someobj.someprop.id;              //do itemid         }          break;          case 'third':              //no use of itemid      }  }  

itemid declared @ top, i'd prefer @ property per case. there doesn't appear immediate reason share variable across different cases. appear nonsense 'invent' different name same.

this written differently, example common pattern in flux architecture.

the problem occures due switch scenario handled single block, irrespective of individual case statments, 'break' statement optional.

rewriting code following should job:

const somefunc(action) => {      if (action.type == 'first'){          let itemid=action.someobj.someprop.id;          //do itemid     }      else if (action.type == 'second'){           let itemid=action.someobj.someprop.id;          //do itemid     }      else { //third           //no use of itemid      }  }  

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -