Tuesday, December 20, 2016

JavaScript Evolution ECMAScript 6 - Simplified Object

Removing Repetition Object

Here is the typical way we write a return object function.
function buildUser(first, last) {
  let fullname = first + " " + last;
  return {first : first, last : last, fullname : fullname};
}
The returned object with keys and variables with the same name is repetitive. We can remove duplicate variables names from object properties when those properties have the same name as the variables being assigned to them.
function buildUser(first, last) {
  let fullname = first + " " + last;
  return {first, last, fullname};
}
This simplicity called Object Initializer Shorthand.

Object Initializer Shorthand can works anywhere, as long as a new object is returned, not just from function.
let first = "Sam";
let last = "Wong";
let userOld = {first : first, last : last};
let userNew = {first, last}; // Simplified

Object Destructing 

Let's look at another side of reading properties from an object.

Here is the typical way we read properties from an object.
let user = buildUser("Sam", "Wong");
let first = user.first;
let last = user.last;
let fullname = user.fullname;
In ES2015, we can read an object's properties using simplified syntax.
let {first, last, fullname} = buildUser("Sam", "Wong");
console.log(first);
console.log(last);
console.log(fullname);
We can read as well as subset return function properties. Below example, we just want to grab the fullname and leave first, last out.
let {fullname} =  buildUser("Sam", "Wong");;
console.log(fullname);

Method Initializer Shorthand

Here is the typical way we write method in function object.
function buildUser(first, last, age) {
  let fullname = first + " " + last;
  const AGE_LIMIT = 18;
  return {
    first,
    last,
    fullname,
    isAgeOverLimit : function () {
      return age >= AGE_LIMIT;
    }
  }
}
With method initializer shorthand, we can simplify by removing the function ().
function buildUser(first, last, age) {
  let fullname = first + " " + last;
  const AGE_LIMIT = 18;
  return {
    first,
    last,
    fullname,
    // Less character and easier to read.
    isAgeOverLimit () {
      return age >= AGE_LIMIT;
    }
  }
}

No comments:

Post a Comment