Skip to content

Instantly share code, notes, and snippets.

@brainysmurf
Last active December 29, 2023 20:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brainysmurf/f99c59d6c591d352d05aa09fe9d1bdae to your computer and use it in GitHub Desktop.
Save brainysmurf/f99c59d6c591d352d05aa09fe9d1bdae to your computer and use it in GitHub Desktop.
Using dynamic property assignments

I was recently wokring on building some objects that had this pattern:

const obj = {
  startRowIndex: 0,
  endRowIndex: 1
}

or

const obj = {
  startColumnIndex: 0,
  endColumnIndex: 1
}

This object is called a GridRange in Google's reference documentation.

The above pattern is useful for declaring to the APIs that the values apply to an entire row, or entire column. It's the same as in A1 notation as doing 1:1 or A1:A.

I considered (for a split second) of using a switch statement, but quickly sought out a more elegant way to code it. Using dynamic properties available in Javascript, one can do this instead:

const type = 'Row';
const obj = {
  [`start${type}Index`]: 0,
  [`end${type}Index`]: 1
}

That way, I just have to determine if type is supposed to be equal to "Row" or "Column", which can be done easily enough with an if statement or ternary statement.

It's a syntax that looks strange at first. But if you think of it as being a shortcut for this:

const obj = {};
const start = 'start' + type + 'Index';
const end = 'end' + type + 'Index';
obj[start] = 0;
obj[end] = 1;

The syntax for dyanamic properties makes a lot more sense.

(Dyanmmic properties aren't usually used to replace switch statements; they are more commonly found when using OOP-like solutions in classes, such as [Symbol.*] etc.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment