29 August 2018

Use curly braces inside JavaScript switch statements

I’ve been working on a react/redux application, and this has led me to use JavaScript switch-statements much more frequency than normal.

I noticed, while looking at someone else’s code, that they were putting curly braces around the statements after every case clause. I have since adopted this as a convention in my own code. While it seems not much different and you do still need to break or return at the end of the statements to prevent fall-through, there are two nice benefits:

  1. Visually the statements appear much more cohesive and more similar to other control structures (for-loop, if-statement, etc.)

  2. The braces create a block scope, this means that you can define unique, scoped variables via let without bumping into the statements in other cases.

To illustrate the second point, here’s some code that could conceivably appear within a redux reducer.

bad.js:

function reducer(state = {}, action) {
  switch (action.type) {
    case "SET_PROPERTY":
      let { key, value } = action.payload;
      return Object.assign({}, state, { [key]: value });
    case "REMOVE_PROPERTY":
      let { key } = action.payload;
      state = Object.assign({}, state);
      delete state[key];
      return start;
  }
}

It’s not immediately obvious that anything is weird here, however the block scope for each case is the entire switch block. As a result, key is being declared with let twice in the same block! If I try to compile this with a JavaScript compilation tool, like Parcel, then I get the following error:

> parcel build bad.js
🚨 bad.js:7:12: bad.js: Duplicate declaration "key"

If we add the curly braces, then the error goes away!

good.js:

function reducer(state = {}, action) {
  switch (action.type) {
    case "SET_PROPERTY": {
      let { key, value } = action.payload;
      return Object.assign({}, state, { [key]: value });
    }
    case "REMOVE_PROPERTY": {
      let { key } = action.payload;
      state = Object.assign({}, state);
      delete state[key];
      return start;
    }
  }
}

Even if you’ve heard it before, reading other people’s code can be a great way to pick up new coding techniques and ideas!




Interested in working with me at Superset to help shape the future of virtual fitness and to empower people to launch their own businesses online? We’re hiring a full-stack engineer. 💪🤓💻 Apply online



Did you find this helpful or fun? paypal.me/mrcoles
comments powered by Disqus

Peter Coles

Peter Coles

is a software engineer living in NYC who is building Superset 💪 and also created GoFullPage 📸
more »

github · soundcloud · @lethys · rss