ES6 Tutorial - Object enhancement
   Jan. 3rd,2018
   Ismail Nassor Mbarack

Objects have been enhanced a lot in ES6.Some juicy syntax got added to them to make them more interactive and easy to manipulate.To kick off we'll start with object shorthand where we don't have to refer both they and value if their variable names are the same.Take a look at the example below.

//this data could be coming from the server,we're just simulating it
function user() {
    let id = 1;
    let username = 'isunaslabs';
    let age = 30;
    let address = 'Nanjing,China';
    //this is how we should have done it in ES5
    //return {id:id,username:username,age:age,address:address};

    //this is how we should do the ES6 way
    return {id,username,age:address};
}

console.log(user());
console.log(user().username);

 

 

 

See how much we reduced our code?Since the key value and the variable we wanna inject to the key have the same name we simply just referred to it once and avoid unnecessary repetition like the way it used to be in ES5.Cool huh!?You may use it a lot if you use Vue JS, when you define a component, if the component name has the same name as the value used in importing it then you could simply refer it only once like the example below

import Vue from 'vue';
import contactList from './components/contact';

new Vue({
   el:'#vue-zone',
   //instead of writing contactList:contactList
   components:{
       contactList
   }
});

 

Next, let's take a look at the other enhancement of objects in ES6, that's object destructuring.

//define a user object
let user = {
    id:1,
    username:'isunaslabs',
    age:30,
    address:'Nanjing,China'
}

let {username,age,theAddress} = user;

//we could retrieve the values in both ES5 and ES6 way
console.log(`The username is:${username}`);
console.log(`The user address is:${theAddress}`);
console.log('The user age is:'+age);

 

Notice in the example above the variable theAddress returned undefined, that's because in object destructuring just like the way it is in object shorthand, names of the object key should be exactly the same as the names of the variables we want to match.In the case above the key names in the left object must be the same as the key names in the right object.

Guess what, object destructuring can also apply when passing function arguments.Let's take a look at the following example.

//the ES5 way
function printUserinfo(obj) {
    console.log('You are '+obj.username+' aged '+obj.age+' years old');
}

function showUserInfo({username,age}) {
    console.log(`You are ${username} aged ${age} years old`);
}

//define a user object
let user = {
    id:1,
    username:'isunaslabs',
    age:30,
    address:'Nanjing,China'
}

printUserinfo(user);
showUserInfo(user);

 

Since all we wanted to pass into the function was the username and the age we didn't have to pass the object into the function,so object destructuring became handy at this point.