onyeePeace

onyeePeace

Object Literals

Description

ES6 provides a cleaner way to define properties and methods on objects.

Example 1:

//Using ES5
var name = "Olowo";
var gender = "Female";

var bio = {
    name: name,
    gender: gender
}
console.log(bio);
//Result will be; {name: "Olowo", gender: "Female"}
console.log(bio.name);
//Result will be; Olowo.

//Using ES6;
var name = "Olowo";
var gender = "Female";

//You don't need to explicity define the values for each property.
var bio = {
    name,
    gender
}
console.log(bio);
//Result will be; {name: "Olowo", belt: "Female"}
console.log(bio.name);
//Result will be; Olowo.
console.log(bio.gender);
//Result will be; Female.

//Adding methods to objects in ES5;
var name = "Olowo";
var gender = "Female";

var bio = {
    name: name,
    gender: gender,
    nationality: function(country){
        console.log(`I am a citizen of ${country}.`)
    }
};
console.log(bio.nationality(Nigeria));
//Result will be; I am a citizen of Nigeria.

//Adding methods to objects in ES6;
var name = "Olowo";
var gender = "Female";

var bio = {
    name: name,
    gender: gender,
    nationality(country){
        console.log(`I am a citizen of ${country}.`)
    }
};
bio.nationality("Nigeria");
//Result will be; I am a citizen of Nigeria.
 
Share this