2 1_writing_modular_code_with_functions
jason.zhu edited this page 2021-05-12 11:46:43 +10:00

Module 1. Writing Modular Code with Functions

Introduction

Topic covers:

  • Functions
  • Arguments
  • Function and Block Scope
  • Immediately Invoked Function Expression (IIFE)
  • Closures

Setting up the Environment

2 files for this learning:

  • app.js
  • index.html

Introducing Functions

Function = a block of organized, reusable code that's used to perform a single, related action.

Steps of using Functions:

  1. Define a function (defails in JavaScript Function Definition)
  2. Invoke a function (details in JavaScript Function Invocation)
// define a function
function greetings(name) {
    console.log('Hello ' + name);
}

// Invoke a function
greetings('John');

Argument vs. Parameter:

  • Argument = a value that we pass to the function when we invoke it
  • Parameter = a variable that we list as part of a function definition

Argument Object: built-in object in JS function (array like object with length property, indexing from 0) used when function was called

When parameter are not given value, it's assigned as NaN (undefined)

Pass argument vs Pass Object:

  • Arguments (JS variable) are passed by Value
  • Objects are passed by reference (as object references are values)

Understanding Function Scope

function greeting() {
    let message = 'Hello';
}
greeting();
console.log(message); // ReferenceError: message is not defined

Nested Function Scope

Variable defined in Function is not available as soon as function finish execution (i.e. out of scope)

function greeting() {
    let message = 'Hello';
    let sayHi = function hi() {
        console.log(message);
    };
    sayHi(); // Hello
}
greeting();

Function can use variables in its parent function's scope

Block Scope

  • Introduced in ES2015
  • Block = code within {}
  • Variables declared with var keyword or within function declarations DO NOT have block scope. Details in diference between var and let
    • "The var variables belong to the global scope when you define them outside a function"
      • var is not limited to block scope {} inside any if-else clause
    • "When you declare a variable inside a function using the var keyword, the scope of the variable is local"
    • for (var i = 0; i < 5; i++){}, here i is global variable. using var means i can still be accessed after for loop.
let message = 'Hello';
if (message === 'Hello') {
    let count = 100; 
}
console.log(count); // Error

where:

  • count is defined within if block
  • As soon as if block is completed, count is out of scope

Immediately Invoked Function Expression (IIFE)

  • Function Expression is used to define a function and assign it to a variable.
  • Immediately Invoked means invoke the function right away when it's defined

regular function

function greeting(){
    console.log('Hello');
}
greeting(); // Hello

IIFE

(funcion() {
    console.log("hello");
}) ();

where:

  • IIFE does not has any name
  • It will be invoked right away

How Closure Work

Local variable within function has short life span, as it's out of scope as function finish execution. But sometime we want to hold the variable (e.g. counter within function), we can use closure.

e.g. w/o closure

let greeting = (function() {
    let message = 'Hello';
    let getMessage = function() {
        return message;
    };
}) ();
console.log(greeting.message); // undefined
  • greeting.message is out of scope
let greeting = (function() {
    let message = 'Hello';
    let getMessage = function(){
        return message;
    };
    // Use closure
    return {
        getMessage: getMessage,
    }
})();
console.log(greeting.getMessage()); // Hello

e.g. closure used for counter

function setupCounter(val){
    return function counter() {
        return val++;
    }
}
let counter1 = setupCounter(0);
console.log(counter1()); // 0
console.log(counter1()); // 1
let counter2 = setupCounter(10);
console.log(counter2()); // 10