Chapter 8. Programming Practices

Every programming language has pain points and inefficient patterns that develop over time. The appearance of these traits occurs as people migrate to the language and start pushing its boundaries. Since 2005, when the term “Ajax” emerged, web developers have pushed JavaScript and the browser further than it was ever pushed before. As a result, some very specific patterns emerged, both as best practices and as suboptimal ones. These patterns arise because of the very nature of JavaScript on the Web.

Avoid Double Evaluation

JavaScript, like many scripting languages, allows you to take a string containing code and execute it from within running code. There are four standard ways to accomplish this: eval(), the Function() constructor, setTimeout(), and setInterval(). Each of these functions allows you to pass in a string of JavaScript code and have it executed. Some examples:

var num1 = 5,
    num2 = 6,

    //eval() evaluating a string of code
    result = eval("num1 + num2"),

    //Function() evaluating strings of code
    sum = new Function("arg1", "arg2", "return arg1 + arg2");

//setTimeout() evaluating a string of code
setTimeout("sum = num1 + num2", 100);

//setInterval() evaluating a string of code
setInterval("sum = num1 + num2", 100);

Whenever you’re evaluating JavaScript code from within JavaScript code, you incur a double evaluation penalty. This code is first evaluated as normal, and then, while executing, another evaluation happens to execute the code contained ...

Get High Performance 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.