Skip to content

Instantly share code, notes, and snippets.

@ianmstew ianmstew/hot-tip.md
Created Nov 8, 2019

Embed
What would you like to do?
imperative vs declarative object initialization
const toggleButtonProps = {
  key: index,
  selected
};
if (props.disabled) toggleButtonProps.disabled = props.disabled;

Hot tip!! Try to challenge yourself to not imperatively update an object or array when you can use ES6 syntax to declare your logic at initialization/object creation time. The progression of developer into declarative/functional programming looks like this:

  1. Beginner (non functional): Think in sequences of steps
  2. Intermediate (becoming functional): Start to think in terms of results with few intermediate steps
  3. Advanced (functional): Think statelessly--there are only inputs and outputs with no intermediate steps

Declarative/functional programming is more readable and less error prone! A good way to get started is to roll conditional initialization logic into your intializers, rather than conditionally modify an already initialized object. In this case, your code would become:

const toggleButtonProps = {
  key: index,
  selected,
  ...(disabled && { disabled })
};

I raised this because in code review I didn't immediately realize disabled was possibly one of the members of this object. The above code makes it perfectly obvious disabled could be part of it. Obviously your code is still correct as-is. This is just a fun way to practice declarative/functional coding and you'll probably find you enjoy it and your code becomes more readable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.