Reading Professional JavaScript (2)

Additional notes while reading the “Professional JavaScript for Web Developers”.

It’s good to have fundamental JavaScript features in the first half of the book. Later part of the book is about HTML/JavaScript on browsers. It’s nicely organized and good reference information, but nowadays, many of the features are accessed through JavaScript frameworks like jQuery, Angular, Ember, etc, and might not be directly applicable.

Some notes from the first half.

Named function expressions

Named function expressions provides a name for functions, which allows to call it recursivly.

// recursion using named function expressions
var factorial = (function f(num) {
  if (num <= 1) {
    return 1;
  }
  else {
    return num * f(num - 1);
  }
});

console.log(factorial(1));  // => 1
console.log(factorial(5));  // => 120

Block Scope

JavaScript doesn’t have block-level scope, but wrapping with anonymous function provides a similar functionality. It allows isolating the variables from the global scope.

// wrapping with anonymous function
(function f() {
  var now = new Date();
  var m = now.getMonth() + 1;
  var d = now.getDate();
  console.log("Today is : " + m + "/" + d);
})();

console.log(now);  // ReferenceError: now is not defined
Advertisements

Posted on March 19, 2013, in Book, JavaScript. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: