Thursday, January 10, 2013

JavaScript - The Good Parts - Part 5

Introduction

This is the fifth post based on the book JavaScript - The Good Parts by Douglas Crockford. The previous post covered details like Closures and Modules. This section covers Curry, some Gotcha in JavaScript, Exceptions and With.

Curry

This allows one to create a new function using an existing function with one or more arguments having a specific value.
Setup the curry function
Function.method ('curry', function () {
    var slice = Array.prototype.slice, args = slice.apply(arguments), that = this;
    return function () {
        return that.apply(null, args.concat(slice.apply(arguments)));
    };
});
Now use this as follows:
var add = add.curry(1);
add1(6); //returns 7
In this manner we can create new functions from existing functions by providing value to one or more of the arguments.

Gotcha

JavaScript does not require one to put a semicolon, but this can lead to some unexpected surprises. Consider this function.
a = function () {
    return
    {
        ok: false;
    };
}
One expects this method to return an object with an attribute "ok" with value "false". But what this actually returns is "undefined". This happens because of the way JavaScript introduces ";". Since there is no semicolon after the keyword "return", JavaScript will put a semicolon after "return" and return "undefined". The rest of the code is ignored.

Converting Strings to Integers

One way to convert String values to integers is to use parseInt(<stringVariable>. The other way to do this would be to compute as follows:
X = 3 + (+"4"); //X = 7
X = 3 + "4";    //X = 34

Exceptions

JavaScript can throw Exception in case of errors. The following are the type of exceptions:
One can throw an exception as follows:
throw new Error(reason);
or
throw {
    name: exceptionName;
    message: reason;
}
One can use a standard try … catch statement to catch Exceptions
try {
} catch (e) {
    switch(e.name) {
        case ‘Error’: 
            …
            break;
        default:
            throw e;
    }
}
There is only one catch clause as there are no Exception classes.
  • Error
  • EvalError
  • RangeError
  • SyntaxError
  • TypeError
  • URIError

With

With can be used to reduce the coding by indicating that we wish to work with attributes/functions of a specified object. But it does not work seamlessly and should be avoided.
with(o) {
    foo = koda;
}
Which of the following is true:
o.foo = koda;
o.foo = o.koda;
foo = o.koda;
foo = koda;
What it actually does is this
if ('foo' in o) {
    o.foo = 'koda' in o ? o.koda : koda;
} else {
    foo = 'koda' in o ? o.koda : koda;
}
Which is logical but given the complexity of the logic, it is better avoided.

No comments: