Beginner's JavaScript Workshop: Fun with Functions!



Beginner's JavaScript Workshop: Fun with Functions!

0 2


javascript-functions

Slides for workshop introducing functions in JavaScript:

On Github LearnToCodeLA / javascript-functions

Learn to Code LA

Beginner's JavaScript Workshop: Fun with Functions!

Created by Liz Krane (@LearningNerd) for Learn to Code LA (@LearnToCodeLA)

Slides: http://learntocodela.github.io/javascript-functions/

What is a function?

What is a function?

"a piece of program wrapped in a value" - Eloquent JavaScript

A "black box" that turns one thing into another thing

"a relation that associates an input to a single output according to some rule." - Wikipedia

JavaScript syntax for functions

// Step 1. Define the function
var getRandomNumber = function() {    
    return 4;
}

// Step 2. Call the function
getRandomNumber();

// Use the output for other stuff!
console.log( getRandomNumber() ); // like this!
var myNum = getRandomNumber(); // or this!
console.log( getRandomNumber() + 5 ); // or even this!

Return values and side effects

// Function with return statement
var getRandomNumber = function() {
    return 4;
}

// Function that relies on side effects
var getRandomNumber = function() {
    console.log("4. Chosen by fair dice roll.");
}

Return values and side effects

Explanation of the joke / Further reading: Wikipedia, StackOverflow, Programmers Stack Exchange

Defining functions with parameters

// Function with no parameters
var myUselessFunction = function() {
    
}

// One parameter
var myUselessFunction = function(myParameter) {
    
}

// Five parameters
var myUselessFunction = function(a,b,c,d,e) {
    
}

Calling functions with arguments

// Defining the function with five parameters
var concatenateFiveStrings = function(a,b,c,d,e) {
    console.log(a + b + c + d + e);
}

// Calling the function with five arguments
concatenateFiveStrings("Hi", "my", "name", "is", "Liz");

// Output in the console: HimynameisLiz

Built-in JavaScript functions

// Console.log, my favorite!
console.log("Hi, I'm a built-in function!");

// A REAL random number function
Math.random();

See the MDN Reference page for a list, or just Google stuff to find all the built-in functions. Gotta call 'em all!

Let's talk about scope!

Things that are outside the scope of this presentation:

  • Quantum mechanics
  • How to bake a souffle
  • Bungee trampolines, my favorite new thing!

Scope in computer science: "the range in which a variable can be referenced" - Wikipedia

Scope in JavaScript

// We start in the global scope! Global variables can be used anywhere.
var globalVar = "This example will work!";

// Define a function                  
var testScope = function() { 
    // This will work because globalVar belongs to the global scope
    console.log(globalVar);
}
// Call the function, and it works!
testScope();

Scope in JavaScript

// Let's try another example. Define a function:
var testScope = function() { 
    // Functions have their own local scope!
    var localVar = "This example won't work!";
}

// This will give an error because localVar only exists
// inside the function in which it was declared:
console.log(localVar);
                  
// Calling the function won't fix it:
testScope();
console.log(localVar); // still won't work

Scope in JavaScript

Just like the word "scope" has multiple meanings in English depending on the context (like variable scope in programming or telescopes in astronomy), variables in JavaScript can have different values within different scopes.

// Define a function:
var myVariable = "This belongs to the GLOBAL scope!";

var testScope = function() { 
    var myVariable = "This belongs to the LOCAL scope!";
    console.log(myVariable);
}

// Compare these two results:
testScope();
console.log(myVariable);

Scope in JavaScript

Now let's change one tiny detail -- we'll remove the "var" keyword from inside our testScope function. See what happens:

// Define a function:
var myVariable = "This belongs to the GLOBAL scope!";

var testScope = function() { 
    // Notice we removed the var keyword in the line below:
    myVariable = "This belongs to the LOCAL scope!";
    console.log(myVariable);
}

// Compare these two results:
testScope();
console.log(myVariable);
// Without the "var" keyword, we're CHANGING the global variable
// instead of creating a new local variable.

Scope in JavaScript

"By treating function-local variables as existing only within the function, the language makes it possible to read and understand functions as small universes, without having to worry about all the code at once."-- Eloquent JavaScript

Different ways to define functions

// Function expression (anonymous function)
var getRandomNumber = function() {
    console.log("4. Chosen by fair dice roll.");
}

// Function declaration
function getRandomNumber() {
    console.log("4. Chosen by fair dice roll.");
}

// Named function expression
var getRandomNumber = function getRandomNumber() {
    console.log("4. Chosen by fair dice roll.");
}    

// Bonus: immediately-invoked function expression (IIFE)
(function getRandomNumber() {
    console.log("4. Chosen by fair dice roll.");
})();

Now for a challenge:

// Challenge 1: What will be the output of this function?
function foo(){
    var bar = function() {
        return 3;
    };
    return bar();
    var bar = function() {
        return 8;
    };
}
alert(foo());
// Challenge 2: What about this one?
function foo(){
    function bar() {
        return 3;
    }
    return bar();
    function bar() {
        return 8;
    }
}
alert(foo());

Variable and function declarations are executed first -- "hoisted" to the top. "Variable Declarations get hoisted but their Assignment Expressions don’t." - See problem/explanation here

// Challenge 1 -- How we wrote the code:
function foo() {
    var bar = function() {
        return 3;
    };
    return bar();
    var bar = function() {
        return 8;
    };
}
alert(foo());
// Challenge 1 -- How the code is actually executed:
function foo() {
    // A declaration for each function expression
    var bar = undefined;
    var bar = undefined;
    // First Function Expression is executed
    bar = function() {
        return 3;
    };
    // Function created by first Function Expression is invoked
    return bar();
    // Second Function Expression unreachable
}
alert(foo()); // 3
// Challenge 2 -- How we wrote the code:
function foo(){
    function bar() {
        return 3;
    }
    return bar();
    function bar() {
        return 8;
    }
}
alert(foo());
// Challenge 2 -- How the code is actually executed:
function foo() {
    // Define bar once
    function bar() {
        return 3;
    }
    // Redefine it
    function bar() {
        return 8;
    }
    // Return its invocation
    return bar(); // 8
}
alert(foo());

Some CodeWars.com practice problems for JavaScript functions:

Thanks!

Code for slides available at: https://github.com/LearnToCodeLA/javascript-functions

Created by Liz Krane (@LearningNerd) for Learn to Code LA (@LearnToCodeLA)

Built with reveal.js

Learn to Code LA Beginner's JavaScript Workshop: Fun with Functions! Created by Liz Krane (@LearningNerd) for Learn to Code LA (@LearnToCodeLA) Slides: http://learntocodela.github.io/javascript-functions/