JavaScript fundamentals by example

Mar 25, 2013 00:00 · 365 words · 2 minute read Programming JavaScript

Iteration

Loop function in JavaScript is similar with other OOP languages.

Foreach loop

var amir =
    {
        name: "amir",
        age: 26
    };

You can go through the object with foreach loop without knowing the number of elements that exist in that object.

(function (obj) {
    for (var arg in obj) {
        alert(arg + ' : ' + obj[arg]);
    }
})(amir);

The input arguments are arrays

You can treat the input arguments as arrays.

function NameLength(newName) {
    var total = '';
    for (i = 0; i < arguments.length; i++) {
        total += arguments[i];
    }
    return total;
}

alert(NameLength("amir"));
alert(NameLength("amir", "John"));

It will get the input arguments and you can go through them with for loop to get the value of each argument.

Recursion

You can call a method in javascript recursively . In other words, a method can call itself from inside.

function factorial(number) {
    if (number === 1 || number === 0) {
        return 1;
    }
    return number * factorial(number - 1);
}
alert(factorial(5));

In the above code , 5 is passing to the factorial method, as it is not equal to 1 or 0 it will call the factorial method with 4. It will consciously do that until it reach to 1 and return 5*4*3*2*1 to the caller.

Closure

The inner function has access to the variables of the outer function.

var OuterFuncVar = "outer function var";
function outer() {
    var OuterVar = "outer var";
    function inner() {
        alert(OuterVar + ' ' + OuterFuncVar);
    }
    inner();
}
outer();

In the code above the Inner() method has access to the OuterFuncVar variable. Closure is a function that works with nonlocal variables that are already executed surrounding the function.

JavaScript closure is a powerful technique . however, in IE there are some source of memory leak for it .

Error handling

Exception can be occur in JavaScript code just like all other programming languages.

(function () {
    try {
        throw {
            name: "errorex",
            message: "some exception occured"
        };
    }
    catch (e) {
        alert(e.name + " : " + e.message);
    }
    finally {
        alert("finally always happen !");
    }
})();

In the above anonymous function, we can throw an exception with name and message and catch it properly.