DEV Community

Nikunj R. Prajapati
Nikunj R. Prajapati

Posted on

Day 1 : Objects in javascript

What is object ?

An object is a collection of properties, and a property is an association between a name (or key) and a value.

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
};
Enter fullscreen mode Exit fullscreen mode

Different ways to create object in javascript

// 1
const obj = new Object();

// 2
const obj = Object.create(null);

// 3 => Most common way
const series = {
     name: "Game of thrones",
     season: 8,
     case: getCast() // can use function as well
};

// 4 => function constructor 
function cast(name) {
  this.name = name;
  this.id = 2;
  this.item = [1,2,3,4
}
var object = new Person("Jon snow");

And Many more..
Enter fullscreen mode Exit fullscreen mode

Tricks and tips

  • To check in object if particular key is exist or not

obj.hasOwnProperty(key) // returns true if key exists otherwise false.

  • To get all properties from an object
const cast = {
  name: 'jon snow',
  age: 22,
  active: false
};

console.log(Object.keys(cast));
// expected output: Array ["name", "age", "active"]
Enter fullscreen mode Exit fullscreen mode

Best practices

Object creation 
// bad
const item = new Object();

// good
const item = {};

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

Use computed property names when creating objects with dynamic property names.
// bad
const obj = {
  id: 5,
  name: 'San Francisco',
};
obj[getKey('enabled')] = true;

// good
const obj = {
  id: 5,
  name: 'San Francisco',

};


Use object method & property shorthand.
// bad
const atom = {
  value: 1,

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

// good
const atom = {
  value: 1,

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

Only quote properties that are invalid identifiers. 
// bad
const bad = {
  'foo': 3,
  'bar': 4,
  'data-blah': 5,
};

// good
const good = {
  foo: 3,
  bar: 4,
  'data-blah': 5,
};

Do not call Object.prototype methods directly, such as hasOwnProperty, propertyIsEnumerable, and isPrototypeOf. 

Why? These methods may be shadowed by properties on the object in question - consider { hasOwnProperty: false } - or, the object may be a null object (Object.create(null)).

// bad
console.log(object.hasOwnProperty(key));

// good
console.log(Object.prototype.hasOwnProperty.call(object, key));

// best
const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.
console.log(has.call(object, key));

/* or */
import has from 'has'; // https://www.npmjs.com/package/has
console.log(has(object, key));


Enter fullscreen mode Exit fullscreen mode

Thanks for reading..

Resource & credits

Top comments (0)