JavaScriptMancy - ES6 - Functions ReCap

by vintharas

JavaScript

// Use babel.js to run these examples

/* JavaScript ES 6 function recap:

- Destructuring
- Default parameters
- Rest parameter
- Arrow functions
- And also:
    - let, spread, const, string templates

*/

/* 

DESTRUCTURING

*/
// You've seen previously how we can use it to 
// extract information from parameters within functions
// with destructuring we can unpack the direction from
// the incoming object and use it right away
console.log("========== Destructuring ==========");
console.log("==== Destructuring within function parameters =====");
function castIceCone(mana, {direction}){ 
    var caster = this || 'God almighty';

    // new template strings
    console.log(`${caster} spends ${mana} mana and casts a terrible ice cone ${direction}`);
}
var jaime = {
    toString: function(){return 'Jaime the Mighty';},
    castIceCone: castIceCone
};
jaime.castIceCone(10, { direction: 'towards Mordor'})
// => Jaime the Mighty spends 10 mana and casts a terrible ice cone towards Mordor

// Use destructuring with objects
console.log("==== Destructuring objects =====");
var jaime = {firstName: 'jaime', 
             lastName: 'the barbarian', 
             height: 178, 
             weight: 90, 
             toString: function() {
                 return "JAIME";
             }};
let {firstName, lastName} = jaime
console.log(`Destructured ${jaime} into firstName '${firstName}' and lastName '${lastName}'`); 
// => Destructured JAIME into firstName 'jaime' and lastName 'the barbarian'

// and using different names than that of the original properties
// (you use the source:destination notation)
let {lastName:title} = jaime;
console.log(`jaime's title is ${title}`);
// => jaime's title is the barbarian

            
console.log("==== Destructuring arrays =====");
// you can even use destructuring with arrays
let [one, two, three] = ['globin', 'ghoul', 'ghost', 'white walker'];
console.log(`one is ${one}, two is ${two}, three is ${three}`)
// => one is globin, two is...