ES6 Syntax Examples III : Rest, Spread Operators & Object Literals

Rest : Rest refers to gathering up parameters and putting them all in to single array.

Spread : Just like Rest but opposite of it. It spreads off an array. Even it's a string.

Let's look at some examples.

Simple Usage of Rest Parameters
'use strict';  
var showManga = function (mangaId, ...categories){  
    console.log(categories)
};
showManga(987,'adventure','scifi');  

Logs: ['adventure','scifi']

It gathers up all the parameters we passed in and put them all in to single array.


What If We Dont Pass Any Parameter?
'use strict';  
var showManga = function (mangaId, ...categories){  
    console.log(categories)
};
showManga(987);  

Logs: []

It still creates an array. But this time it's an empty array.


What Happens If We Create a New Dynamic Function ?
'use strict';  
var showManga = new Function("..categories","return categories");  
console.log(showManga('adventure','scifi'));  

Logs: ['adventure','scifi']


Simple Usage of Spread Operator
'use strict';  
var name = "OGPOYRAZ";  
var nameInArray = [...name];  
console.log(nameInArray);  

Logs: ['O','G','P','O','Y','R','A','Z']

So it's simply spreads the array.

New Type of Object Literal
'use strict';  
var name = "Goktug",lastname = "Poyraz";  
var person = {  
    name,
    lastname
}
console.log(person);  

Logs: {name:"Goktug",lastname:"Poyraz"}


Functions in Object
'use strict';  
var name = "Goktug",lastname = "Poyraz";  
var person = {  
    name,
    lastname,
    showFullName () {
        console.log(this.name+' '+this.lastname);
    }
}
person.showFullName();  

Logs: Goktug Poyraz


this Keyword in Object Literal Points To Object
'use strict';  
var name = "Goktug",lastname = "Poyraz";  
var person = {  
    name : "Omer",
    lastname : "Karayel",
    showFullName () {
        console.log(this.name+' '+this.lastname);
    }
}
person.showFullName();  

Logs: Omer Karayel


Dynamic Field in Object
'use strict';  
var name = "Goktug",lastname = "Poyraz";  
var newField = 'ID',id = 987;  
var person = {  
    name,
    lastname,
    [newField] : id
}
console.log(person.ID);  

Logs: 987