Skip to content

Latest commit

 

History

History
153 lines (114 loc) · 2.41 KB

File metadata and controls

153 lines (114 loc) · 2.41 KB


Objects

  • 3.1 Use the literal syntax for object creation.
// bad
const item = new Object();

// good
const item = {};
// bad
const superman = {
  default: { clark: 'kent' },
  private: true
};

// good
const superman = {
  defaults: { clark: 'kent' },
  hidden: true
};
  • 3.3 Use readable synonyms in place of reserved words.
// bad
const superman = {
  class: 'alien'
};

// bad
const superman = {
  klass: 'alien'
};

// good
const superman = {
  type: 'alien'
};

  • 3.4 Use computed property names when creating objects with dynamic property names.

Why? They allow you to define all the properties of an object in one place.

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

// bad
const obj = {
  id: 5,
  name: 'San Francisco',
};
obj[getKey('enabled')] = true;

// good
const obj = {
  id: 5,
  name: 'San Francisco',
  [getKey('enabled')]: true,
};

  • 3.5 Use object method shorthand.
// bad
const atom = {
  value: 1,

  addValue: function (value) {
    return atom.value + value;
  },
};

// good
const atom = {
  value: 1,

  addValue(value) {
    return atom.value + value;
  },
};

  • 3.6 Use property value shorthand.

Why? It is shorter to write and descriptive.

const lukeSkywalker = 'Luke Skywalker';

// bad
const obj = {
  lukeSkywalker: lukeSkywalker
};

// good
const obj = {
  lukeSkywalker
};
  • 3.7 Group your shorthand properties at the beginning of your object declaration.

Why? It's easier to tell which properties are using the shorthand.

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

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

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