Accustoming Yourself to JavaScript
- Item 1: Know Which JavaScript You Are Using
- Item 2: Understand JavaScript's Floating-Point Numbers
- Item 3: Beware of Implicit Coercions
- Item 4: Prefer Primitives to Object Wrappers
- Item 5: Avoid using == with Mixed Types
- Item 6: Learn the Limits of Semicolon Insertion
- Item 7: Think of Strings As Sequences of 16-Bit Code Units
JavaScript was designed to feel familiar. With syntax reminiscent of Java and constructs common to many scripting languages (such as functions, arrays, dictionaries, and regular expressions), JavaScript seems like a quick learn to anyone with a little programming experience. And for novice programmers, it’s possible to get started writing programs with relatively little training thanks to the small number of core concepts in the language.
As approachable as JavaScript is, mastering the language takes more time, and requires a deeper understanding of its semantics, its idiosyncrasies, and its most effective idioms. Each chapter of this book covers a different thematic area of effective JavaScript. This first chapter begins with some of the most fundamental topics.
Item 1: Know Which JavaScript You Are Using
Like most successful technologies, JavaScript has evolved over time. Originally marketed as a complement to Java for programming interactive web pages, JavaScript eventually supplanted Java as the web’s dominant programming language. JavaScript’s popularity led to its formalization in 1997 as an international standard, known officially as ECMAScript. Today there are many competing implementations of JavaScript providing conformance to various versions of the ECMA-Script standard.
The third edition of the ECMAScript standard (commonly referred to as ES3), which was finalized in 1999, continues to be the most widely adopted version of JavaScript. The next major advancement to the standard was Edition 5, or ES5, which was released in 2009. ES5 introduced a number of new features as well as standardizing some widely supported but previously unspecified features. Because ES5 support is not yet ubiquitous, I will point out throughout this book whenever a particular Item or piece of advice is specific to ES5.
In addition to multiple editions of the standard, there are a number of nonstandard features that are supported by some JavaScript implementations but not others. For example, many JavaScript engines support a const keyword for defining variables, yet the ECMAScript standard does not provide any definition for the syntax or behavior of const. Moreover, the behavior of const differs from implementation to implementation. In some cases, const variables are prevented from being updated:
const PI =3.141592653589793
; PI ="modified!"
; PI; // 3.141592653589793
Other implementations simply treat const as a synonym for var:
const PI =3.141592653589793
; PI ="modified!"
; PI; // "modified!"
Given JavaScript’s long history and diversity of implementations, it can be difficult to keep track of which features are available on which platform. Compounding this problem is the fact that JavaScript’s primary ecosystem—the web browser—does not give programmers control over which version of JavaScript is available to execute their code. Since end users may use different versions of different web browsers, web programs have to be written carefully to work consistently across all browsers.
On the other hand, JavaScript is not exclusively used for client-side web programming. Other uses include server-side programs, browser extensions, and scripting for mobile and desktop applications. In some of these cases, you may have a much more specific version of JavaScript available to you. For these cases, it makes sense to take advantage of additional features specific to the platform’s particular implementation of JavaScript.
This book is concerned primarily with standard features of JavaScript. But it is also important to discuss certain widely supported but nonstandard features. When dealing with newer standards or nonstandard features, it is critical to understand whether your applications will run in environments that support those features. Otherwise, you may find yourself in situations where your applications work as intended on your own computer or testing infrastructure, but fail when you deploy them to users running your application in different environments. For example, const may work fine when tested on an engine that supports the nonstandard feature but then fail with a syntax error when deployed in a web browser that does not recognize the keyword.
ES5 introduced another versioning consideration with its strict mode. This feature allows you to opt in to a restricted version of JavaScript that disallows some of the more problematic or error-prone features of the full language. The syntax was designed to be backward-compatible so that environments that do not implement the strict-mode checks can still execute strict code. Strict mode is enabled in a program by adding a special string constant at the very beginning of the program:
"use strict"
;
Similarly, you can enable strict mode in a function by placing the directive at the beginning of the function body:
functionf
(x) {"use strict"
; // ... }
The use of a string literal for the directive syntax looks a little strange, but it has the benefit of backward compatibility: Evaluating a string literal has no side effects, so an ES3 engine executes the directive as an innocuous statement—it evaluates the string and then discards its value immediately. This makes it possible to write code in strict mode that runs in older JavaScript engines, but with a crucial limitation: The old engines will not perform any of the checks of strict mode. If you don’t test in an ES5 environment, it’s all too easy to write code that will be rejected when run in an ES5 environment:
functionf
(x) {"use strict"
; var arguments = []; // error: redefinition of arguments // ... }
Redefining the arguments variable is disallowed in strict mode, but an environment that does not implement the strict-mode checks will accept this code. Deploying this code in production would then cause the program to fail in environments that implement ES5. For this reason you should always test strict code in fully compliant ES5 environments.
One pitfall of using strict mode is that the "use strict" directive is only recognized at the top of a script or function, which makes it sensitive to script concatenation, where large applications are developed in separate files that are then combined into a single file for deploying in production. Consider one file that expects to be in strict mode:
// file1.js"use strict"
; functionf
() { // ... } // ...
and another file that expects not to be in strict mode:
// file2.js
// no strict-mode directive
function g
() {
var arguments = [];
// ...
}
// ...
How can we concatenate these two files correctly? If we start with file1.js, then the whole combined file is in strict mode:
// file1.js"use strict"
; functionf
() { // ... } // ... // file2.js // no strict-mode directive functionf
() { var arguments = []; // error: redefinition of arguments // ... } // ...
And if we start with file2.js, then none of the combined file is in strict mode:
// file2.js // no strict-mode directive functiong
() { var arguments = []; // ... } // ... // file1.js"use strict"
; functionf
() { // no longer strict // ... } // ...
In your own projects, you could stick to a “strict-mode only” or “nonstrict-mode only” policy, but if you want to write robust code that can be combined with a wide variety of code, you have a few alternatives.
Never concatenate strict files and nonstrict files. This is probably the easiest solution, but it of course restricts the amount of control you have over the file structure of your application or library. At best, you have to deploy two separate files, one containing all the strict files and one containing the nonstrict files.
Concatenate files by wrapping their bodies in immediately invoked function expressions. Item 13 provides an in-depth explanation of immediately invoked function expressions (IIFEs), but in short, by wrapping each file’s contents in a function, they can be independently interpreted in different modes. The concatenated version of the above example would look like this:
// no strict-mode directive (function() { // file1.js"use strict"
; functionf
() { // ... } // ... })(); (function() { // file2.js // no strict-mode directive functionf
() { var arguments = []; // ... } // ... })();
Since each file’s contents are placed in a separate scope, the strict-mode directive (or lack of one) only affects that file’s contents. For this approach to work, however, the contents of files cannot assume that they are interpreted at global scope. For example, var and function declarations do not persist as global variables (see Item 8 for more on globals). This happens to be the case with popular module systems, which manage files and dependencies by automatically placing each module’s contents in a separate function. Since files are all placed in local scopes, each file can make its own decision about whether to use strict mode.
Write your files so that they behave the same in either mode. To write a library that works in as many contexts as possible, you cannot assume that it will be placed inside the contents of a function by a script concatenation tool, nor can you assume whether the client codebase will be strict or nonstrict. The simplest way to structure your code for maximum compatibility is to write for strict mode but explicitly wrap the contents of all your code in functions that enable strict mode locally. This is similar to the previous solution, in that you wrap each file’s contents in an IIFE, but in this case you write the IIFE by hand instead of trusting the concatenation tool or module system to do it for you, and explicitly opt in to strict mode:
(function() {"use strict"
; functionf
() { // ... } // ... })();
Notice that this code is treated as strict regardless of whether it is concatenated in a strict or nonstrict context. By contrast, a function that does not opt in to strict mode will still be treated as strict if it is concatenated after strict code. So the more universally compatible option is to write in strict mode.
Things to Remember
- Decide which versions of JavaScript your application supports.
- Be sure that any JavaScript features you use are supported by all environments where your application runs.
- Always test strict code in environments that perform the strict-mode checks.
- Beware of concatenating scripts that differ in their expectations about strict mode.