Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

>I'm sorry, but in my decade of JavaScript I never read anything more cryptic than this. What is this supposed to mean?

Switches in JS are just implicit maps.

  const caseVal = 'case1';

  const result = ({
   'case1': (()=> 'case1Val'),
   'case2': (()=> 'case2Val'),
   'case3': (()=> 'case3Val'),
  } [caseVal] || (()=> 'default'))()
Has identical performance to a switch case and is far more idiomatic.


Thanks for the example!

I assume the identical performance just comes from the optimization of the JIT, as allocating objects in the heap seems quite overkill for such a control flow. I only fall back to this when switch/case isn't available in the language, eg. in Python.

Is this a thing in the JS community?




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: