JavaScriptmancy - Basics - Functions - Function Overload

by vintharas

HTML

<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 for C# Devs
Chapter 05 - The Basics of JavaScript Functions - Function Overloading

*/

randalf.sighs();
randalf.says("it didn't last long at all");
randalf.says("You know? Not everyone could tap into the power of the REPL...");

randalf.says(`
Only a few could harness it. And some of them, some of them were crooked, either
that or they just couldn't handle the power.

Before Branden could do anything about it, they shattered the world, enslaved the normals, herded and annihilated those of us who opposed them and that's the state of things. 

We are governed by a bunch of egocentric megalomaniac mad men and women.
`);


mooleen.says("How is it that you're still here then?");
randalf.says("Well they did something worse to me. They took it");

mooleen.says("You cannot cast spells any more?");
randalf.says("I cannot. But I do remember everything");
randalf.says("Talking about knowledge. " + 
             "Have you heard about the marvels of overloading?");


console.log("============ Function Overloading in JS ===============\n\n")

console.log("============ The Problem With Function Overloading ======\n")
// One does not simply overload functions in JavaScript willy nilly
function raiseSkeleton(){
    console.log('You raise a skeleton!!!');
}

function raiseSkeleton(mana){
    console.log('You raise ' + mana + ' skeletons!!!');
}

raiseSkeleton();
// => You raise undefined skeletons!!!
// functions get overwritten if you declare them multiple times, even if they have different signatures


console.log("\n\n====== Function overloading by inspecting arguments ======\n")
// Instead
// #1 you can do argument checking, which sucks
// - less readable and maintainable
function raiseSkeletonWithArgumentInspecting(){
    if (typeof arguments[0] === "number"){
       ...