This book is a bit unusual, in that I discuss both client-side (browser) and server-side (Node.js) code. That reflects the uniquely portable nature of JavaScript. The central concepts apply to all JavaScript environments, but certain examples are aimed at one or the other.
Even if you have no interest in writing Node applications, I hope you’ll follow along by running these code snippets locally. See Running Code in Node.js for directions.
When you see a code snippet with a filename, that means it’s self-contained and can be run without modification. Here’s an example:
Preface/stringConstructor.js | |
| console.log('str'.constructor.name); |
The surrounding context should make it clear whether the code is runnable in the browser, in Node.js, or in both.
When a code snippet doesn’t have a filename, that means it’s not self-contained. It may be part of a larger example, or it may be a hypothetical. Here’s an example:
| var tenSeconds = 10 * 1e3; |
| setTimeout(launchSatellite, tenSeconds); |
These examples are meant to be read, not run.
Node is very easy to install and use: just head to http://nodejs.org/, click Download, and run the Windows or OS X installer (or build from source on *nix). You can then run node from the command line to open a JavaScript REPL (analogous to Ruby’s irb environment).
| $ node |
| > Math.pow(5, 6) |
| 15625 |
You can run a JavaScript file by giving its name as an argument to the node command.
| $ echo "console.log(typeof NaN)" > foo.js |
| $ node foo.js |
| number |
Every modern browser provides a nice little REPL that lets you run JavaScript code in the context of the current page. But for playing with multiline code examples, you’re better off using a web sandbox like jsFiddle.[12]
With jsFiddle, you can enter JavaScript, HTML, and CSS, and then click Run (or press Ctrl+Enter) to see the result. (console output will go to your developer console.) You can bring in a framework like jQuery by choosing it in the left sidebar. And you can save your work, giving you a shareable URL.
18.191.233.15