JavaScriptmancy - Basics - Functions
Basic ways to declare functions in JavaScript
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
Chapter 02 - The Basics of JavaScript Functions
*/
/*
* ...In the previous chapter...
* stranger.says('...err... who the hell are you? and whaaaat is a kender?!');
*
*/
randalf.says(`Well... I am Randalf. Randalf the Red... JavaScriptmancer
of the First Order... Guardian of the Sacred Flame...
Freedom fighter and Poet...`);
stranger.says('uh?');
randalf.says(`Yes! And you are the Chosen one! The Child of Prophecy!
The one that will bring balance to the force! Muad'Dib! The Dragon reborn!
Brought to this land in the twelfth moon of the twelfth month of the
twelfth year of the Wyrm to save the world from certain destruction!`);
stranger.says(`I am Mooleen actually...
and this is the weirdest dream I've ever had...`);
let mooleen = stranger;
randalf.says(`There's no time for this child. You need to learn how to
defend yourself, it isn't safe here... It all starts with functions,
functions are the key...`);
narrate("============= Function Are The Key... =============");
// there's two ways to write functions in javascript
// function expressions:
// anonymous function expression
var castFireballSpellExpression = function(){
// chaos and mayhem
};
// and function declarations
function castFireballSpellDeclaration(){
// it's getting hot in here...
}
narrate("======= Function Expresssions =============");
// We use the *function expression* style whenever we declare a function like an expression, either by assigning it to a variable:
// an anonymous function expression
var castFireballSpell = function(){
console.log('...chaos and mayhem');
};
castFireballSpell();
// => ...chaos and mayhem
// another anonymous function expression as a property of an object
var magician = {
castFireballSpell: function() {
...