CHAPTER ELEVEN

JavaScript Is…

Science is what we understand well enough to explain to a computer. Art is everything else we do.

Donald Knuth

I understand there are people in this world who do not like JavaScript. I’ve gotten into enough late-night battles about CoffeeScript to have heard all the vitriol. I’ve been generally unmovable about this. I think curly braces are elegant, I think semicolons are enchanting, and I think duck typing is adorable. I thought writing this chapter would be a good opportunity to share my favorite things about JavaScript.

JavaScript Is Dynamic

JavaScript takes advantage of virtual machines for just-in-time (JIT) compilation (see V8, Node.js, and Spider Monkey for some examples). JavaScript makes excellent use of closures by having variables that exist both on the global level and the functional level.

Consider this function:

function CheckForPrefix(name){
  var prefix = "Dr.";

  if (name.indexOf(prefix) == -1)
    return function AddPrefix(){
      return prefix + name;
    }
}

JavaScript’s closures give us the ability to reference variables defined in the containing function. In this instance it enables us to keep the separation of concerns while not repeating ourselves at the same time.

JavaScript has an eval function that allows us to concatenate values and evaluate them at runtime. eval makes things slower, as it adds a compilation step, so it’s to be used sparingly; however, it does allow us to create macros, which are another dynamic ...

Get Beautiful JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.