ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • First-Class Functions and IIFE
    DynamicPL/Javascript 2019. 10. 24. 00:31

    1. Overview

    We can pass functions as arguments and return it and store it into variables because functions are always first-class functions in Javascript because they are effectively objects.

    2. Description

    2.1 Passing Functions as Arguments

    These functions are called "callback function" because they are functions that we pass into functions that will then call them later.

    var years = [1990, 1965, 1937, 2005, 1998];
    
    function arrayCalc(arr, fn) {
        var arrRes = [];
        for (var i = 0; i < arr.length; i++) {
            arrRes.push(fn(arr[i]));
        }
        return arrRes;
    }
    
    function calculateAge(el) {
        return 2016 - el;
    }
    
    function isFullAge(el) {
        return el >= 18;
    }
    
    function maxHeartRate(el) {
        if (el >= 18 && el <= 81) {
            return Math.round(206.9 - (0.67 * el));
        } else {
            return -1;
        }
    }
    
    
    var ages = arrayCalc(years, calculateAge);
    var fullAges = arrayCalc(ages, isFullAge);
    var rates = arrayCalc(ages, maxHeartRate);
    
    console.log(ages);
    console.log(rates);

    2.2 Functions Returning Functions

    We can return anonymous function inside of parent function which doesn't have a name.

    function interviewQuestion(job) {
        if (job === 'designer') {
            return function(name) {
                console.log(name + ', can you please explain what UX design is?');
            }
        } else if (job === 'teacher') {
            return function(name) {
                console.log('What subject do you teach, ' + name + '?');
            }
        } else {
            return function(name) {
                console.log('Hello ' + name + ', what do you do?');
            }
        }
    }
    
    var teacherQuestion = interviewQuestion('teacher');
    var designerQuestion = interviewQuestion('designer');
    
    
    teacherQuestion('John');
    designerQuestion('John');
    designerQuestion('jane');
    designerQuestion('Mark');
    designerQuestion('Mike');
    
    interviewQuestion('teacher')('Mark');

    2.3 Immediately Invoked Function Expression(IIFE)

    If the only purpose is to hide some variable from the outside which means creating a private variable, then we don't need to declare a whole function with a name and then call it. Instead, using IIFE. Functions without the name and parentheses, then the Javascript parser would think that this is a function declaration but since we don't have any name, then it throws an error.

    And the solution is to wrap the entire thing into parentheses because what's inside of parenthesis cannot be a statement but treat this as an expression in Javascript. And only we can do is invoke the function because if we didn't do this, it would never be called and never do anything since we don't attach this to a variable. We can no longer access inside variables from the outside which are private.

    We can call IIFE only once because this function is not assigned to any variable. But that's not the problem because in this case, we are not using the function to create a piece of reusable code, but to create a new scope that is hidden from the outside scope. So where we can safely put variables that give us data privacy and modularity.

    function game() {
        var score = Math.random() * 10;
        console.log(score >= 5);
    }
    game();
    
    
    (function () {
        var score = Math.random() * 10;
        console.log(score >= 5);
    })();
    
    //console.log(score);
    
    
    (function (goodLuck) {
        var score = Math.random() * 10;
        console.log(score >= 5 - goodLuck);
    })(5);

    3. References

    https://codingheroes.io/

    'DynamicPL > Javascript' 카테고리의 다른 글

    let, const, block scope, function scope and IIFEs  (0) 2019.10.24
    Bind, Call and Apply  (0) 2019.10.24
    Primitives vs. Objects  (0) 2019.10.24
    Classes and subclasses  (0) 2019.10.23
    Promises, Promisification, Async, Await, and Ajax  (0) 2019.10.23

    댓글

Designed by Tistory.