JavaScriptmancy - ES6 - Functions - Default Parameters

by vintharas

JavaScript

// run on babeljs or tdd bin
    "use strict";

    function castIceCone(mana=5){
        // we take advantage of the || operator to define defaults
        var caster = this || 'God almighty';
        console.log(`${caster} spends ${mana} mana and casts a terrible ice cone`);          
    }
    
    castIceCone();
    // => God almighty spends 5 mana and casts a terrible ice cone
    
    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
    
    // run on Babel
    // defaults are not limited to constant values, 
    // you can even use objects
    function castIceConePro(mana=22, {direction='in front of you'}={}){
        var caster = this || 'God almighty';
        
        console.log(`${caster} spends ${mana} mana and casts a terrible ice cone ${direction}`);
    }

    castIceConePro();
    // => God almighty spends 22 mana and casts a terrible ice cone in front of you   
    
    var jaime = {
        toString: function(){return 'Jaime the Mighty';},
        castIceConePro: castIceConePro
    };
    jaime.castIceConePro(10, { direction: 'towards Mordor'})
    // => Jaime the Mighty spends 10 mana and casts a terrible ice cone towards Mordor

    // defaults are not limited to constant values
    // you can even use callbacks!
    function castSpell(spell=function(){console.log('holy shit a callback');}){
        spell();
    }
    
     castSpell();
     // => holy shit a callback
     castSpell(function(){console.log("balefire!!!! You've been wiped out of existence");}); 
     // => balefire!!!! You've been wiped out of existence