JavaScriptmancy - Basics - Functions - Default Values

Defaults in javascript

by vintharas

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<pre><code id="theWorld">
</code></pre>

CSS

pre { 
    font-size: 0.9rem; 
    padding: 2%;
    background: #333; 
    color: white;
}

pre .world {
    display: block;
    white-space: pre-wrap;
}

pre .world-error{
    color: rgba(255,0,0,0.7);
}

pre .world-info {
    color: grey;
    font-style: italic;
    padding: 10px 0;
}

pre .world-spell{
    color: rgba(90,90,255,1);
}

Babel + JSX

'use strict'
// log stuff in the home-made console to the write in addition to
// logging it to the browser console
startWorld();

/*

JavaScript-mancy: Mastering the Arcane Art of Writing Awesome JavaScript
Chapter 03 - The Basics of JavaScript Functions - Default Arguments

*/

/* 
  * A distant sound....
  *
  * A booming sound...
  * 
  * Or a... the flapping of the wings of some giant bird
  * 
  * Salt in your mouth...
  * 
  * clap! clap! clap!
  */ 

randalf.says('Well that was close... but I am impressed!');
 
mooleen.wakesUp(['slowly', 'groggily']);
mooleen.laughsWeakly();

/*
 *   Mooleen awakes to an infinite sea, a vast ocean, and dunes
 *   as far as the eye can see.
 */

mooleen.says('I am a fast learner...')
mooleen.says('And now I want to learn what' + 
 ' the heck is going on?');
 
 randalf.says('There will be time for that soon. ' + 
     'Now you need to recover.');
 
 mooleen.says('but...');
 
 randalf.says('You know... I think you can add some improvements ' + 
'to those spells... I know a couple of tricks...have you heard of defaults?');

narrate("***** Defaults with the || operator *****\n");
function castIceCone(mana, options){
    // we take advantage of the || operator to define defaults
    var mana = mana || 5,
        options = options || {direction: 'in front of you', damageMod: 10},
        direction = options.direction || 'in front of you',
        damageMod = options.damage || 10,
        damage = 2*mana + damageMod;
    
    console.log("You spend " + mana + " mana and casts a terrible ice cone " + direction + " (" + damage + " DMG).");
}

castIceCone();
// => You spend 5 mana and casts a terrible ice cone in front of you (20 DMG)
castIceCone(10);
// => You spend 5 mana and casts a terrible ice cone in front of you (20 DMG)
castIceCone(10, { damage: 200});
// => You spend 5 mana and casts a terrible ice cone in front of you (220 DMG)
castIceCone(10, { direction: 'towards Mordor'})
// => You spend 10 mana and casts a terrible ice...