Evaluating local variables

As we have seen in the previous example, omitting the let or var keyword in front of the declaration of a local variable makes it global. In all cases, functions and objects should not be able to create functional side effects by modifying the value of variables outside of their local scope. Thus, the let keyword should always be used when declaring variables inside the scope of a function or structure. For example, simply moving global variables to the local scope of a function that is using them within a local loop translates into almost a 30% increase in performance in most browsers.

Also, when declaring variables with the let keyword, you get to use block scope, which should be used as much as possible. Thus, a variable used within a for loop will not stay within scope once the loop is done. This allows for better variable encapsulation and isolation, more efficient garbage collection and better performance in general.

One way to easily keep track of variable declarations is to use JavaScript’s strict mode. We will explain this ES5 feature in more detail in the next section of this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset