O'Reilly logo

CoffeeScript Programming with jQuery, Rails, and Node.js by Michael Erasmus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

CoffeeScript handles scope better

Take a look at the following snippet of JavaScript. Notice that a variable called salutation gets defined in two places, inside the function, as well as after the function gets called the first time:

JavaScript

var greet = function(){ 
    if(typeof salutation === 'undefined') 
        salutation = 'Hi!'; 
    console.log(salutation); 
}
greet();
salutation = "Bye!";
greet();

In JavaScript, when you omit the var keyword while declaring a variable, it immediately becomes a global variable. Global variables are available in all scopes, and thus can be overwritten from anywhere, which often ends up as being a mess.

In the previous example, the greet function first checks if the salutation variable is defined (by checking if typeof ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required