Study Airbnb JavaScript style

Oct 28, 2019

Study Airbnb JavaScript style

How to define a Object?


function getKey(k) {
  return `a key named ${k}`;
}

// good
const obj = {
  id: 5,
  name: 'San Francisco',
  [getKey('enabled')]: true,
  getValue(v) {
    return v + this.name;
  }
};

Use property value shorthand. And group your shorthand properties at the beginning of your object declaration.

const episodeThree = 2;
const lukeSkywalker = 'Luke Skywalker';
const anakinSkywalker = 'Anakin Skywalker';

// bad
const obj = {
  episodeOne: 1,
  twoJediWalkIntoACantina: 2,
  lukeSkywalker,
  episodeThree: episodeThree,
  mayTheFourth: 4,
  anakinSkywalker,
};

// good
const obj = {
  lukeSkywalker,
  anakinSkywalker,
  episodeThree,
  episodeOne: 1,
  twoJediWalkIntoACantina: 2,
  mayTheFourth: 4,
};