Post/Code

HomeAboutUsesNow

Eloquent JavaScript Chapter 3: Functions.

  • Recursion - Generally, recursion can be up to 10 times slower than looping. However, recursion can be more elegant, as such, the programmer must determine whether efficiency or simplicity is more appropriate.

    
    function power(base, exponent) {
        if (exponent == undefined) {
            exponent = 2;
        }
    
        var result = 1;
    
        for (var count = 0; count < exponent; count++) {
            result *= base;
        }
        
        return result;
    }
    
    function powerR(base, exponent) {
        if (exponent == 0)
            return 1;
        else
            return base * power(base, exponent - 1);
    }
    
    console.log("Recursive: ", powerR(2, 3));
    console.log("Loop: ", power(2,3));
    
* Closures - The ability to reference an instance of a local variable in an enclosing function.
function multiplier(factor) {
    return function(number) {
            console.log("Factor: ", factor, " Number: ", number);
            return number * factor;
        };
    }
var twice = multiplier(3);
console.log(twice(5));
* Lexical scope is the variable 'visibility' of variables within a program via combinations of scope. Essentially, local scopes have access to those scope around them. They do not have access to scopes inside of them. * Function declarations can be placed anywhere within the program as they are effectively hoisted to the top of the scope when running.
    foo('bar');
    // function declaration
    function foo(string) {
        console.log('Foo', string);
    }
  • Expression functions need to be declared before they are used.

    // function definition
    var foo = function(string) {
        return 'Foo' + string;
    }
    console.log(foo('bar'));
    
  • In JavaScript you can have optional arguments/parameters. If there are too many, the extras get ignored. If there are too few, the missing params get undefined.
  • There are basically two ways functions are introduced: Replication - You find there is code repeated in your program and you write a function to remove this repetition. Purpose - You have something you need to do, so you write a function to do it.
'How difficult it is to find a good name for a function is a good indication of how clear a concept it is that you’re trying to wrap.' - Marijn Haverbeke
  • There are generally three types of functions: Pure functions - return values and receive values, they do not access global variables or have side effects. They do not rely on side-effects from elsewhere. Side effect functions - do not return a value and typically adjust globals. These can be difficult to reason about. Combination functions - these are functions that combine both the approaches