הלינקייה: מגזין חודשי למפתחים

רוצה לשמוע על כל האירועים, המדריכים, הקורסים והמאמרים שנכתבו החודש ?
הלינקייה הינו מגזין חופשי בעברית שמשאיר אותך בעניינים.
בלי ספאם. בלי שטויות. פעם בחודש אצלך בתיבה.

JavaScript

02 JavaScript Syntax from Ynon Perek

JavaScript DOM Manipulations from Ynon Perek

03 Advanced JavaScript from Ynon Perek

Scalable JavaScript from Ynon Perek

JavaScript Array Example

(function() {
 
    var numbers = [1, 2, 3, 4, 5],
        empty   = [];
 
    var dbl = function(x) {
        return x * 2;        
    };
 
    empty[10] = 'hello';
    empty[11] = 'world';
    empty[50] = 10;
 
    console.log(empty[10] + ' ' + empty[11]);
 
    var map = function(f, arr) {
        var len = arr.length, i, el,
            results = [];
 
        for ( i=0; i < len; ++i ) {
            el = arr[i];
 
            if ( el !== undefined ) {
                results[i] = f(el);
            }
        }
 
        return results;
    };
 
    console.log(map(dbl, numbers));
 
}());

Functions Examples

Functions in JavaScript are a basic concept of the language, and are the tool to implement modular and reusable code.

Below are the examples for common usages of functions, all were tested using node.js.

Implementing Modules

(function(global) {
    // private variable
    var registers = {};

    // private function
    function check_or_init_register(reg_id) {
        if ( typeof(registers[reg_id]) === 'undefined' ) {
            registers[reg_id] = 0;
        }
    }

    // public namespace - implemented as an object
    global.Calculator = {};

    // public functions on the Calculator namespace
    global.Calculator.add_to_register = function(reg_id, x) {
        check_or_init_register(reg_id);

        registers[reg_id] += x;
    }

    global.Calculator.sub_from_register = function(reg_id, x) {
        check_or_init_register(reg_id);

        registers[reg_id] -= x;
    }

    global.Calculator.zero_register = function(reg_id, x) {
        registers[reg_id] = 0;
    }

    global.Calculator.read_register = function(reg_id) {
        check_or_init_register(reg_id);

        return registers[reg_id];
    }

}(this));

// in node.js exports is the global object
exports.Calculator.add_to_register(10, 7);
exports.Calculator.add_to_register(10, 5);
console.log(exports.Calculator.read_register(10));

Configuration Objects

(function() {
    // Taking many arguments is confusing
    // caller must remember them all, and their order
    // What's worse, with no compiler on our side, a
    // bug will attack sooner or later
    function Student_Antipattern(name, age, avg_grade, year, university) {

        if ( typeof(name) === 'undefined' ) {
            throw 'name is a must';
        }

        var that = {
            name       : name,
            age        : age  || 17,
            avg_grade  : avg_grade || 60,
            year       : year || 1,
            university : university || "Space Travel Academy"
        };

        return that;
    }

    // Using a configuration object, we can avoid the trouble
    // of remembering argument order
    // The function writer is also more aware that some
    // arguments may not be passed, and able to handle this
    // Finally, it is easier to use optional arguments with
    // a configuration object
    function Student(info) {
        if ( typeof(info.university) === 'undefined' ) {
            throw 'university is a must';
        }

        var that = {
            name       : info.name      || "Anonymous",
            age        : info.age       || 17,
            avg_grade  : info.avg_grade || 60,
            year       : info.year      || 1,
            university : info.university
        }
    }

    Student_Antipattern("John");
    Student({ name : "James", year : 3 });

}());