Chapter 2. JavaScript Development

If you’re new to JavaScript, understanding the language itself is only half the battle. You might reasonably have questions like:

  • How do I name and organize my files?

  • How do I run my code?

  • How do I track changes as my application grows?

  • How can I ensure consistency and quality in my code?

Don’t think of this chapter as a distraction from the topic at hand (JavaScript). Think of it as a practical introduction to some important tools and techniques that are commonly used in JavaScript development.

Prerequisites

This chapter assumes you’re comfortable using your computer’s terminal (command-line interface). This isn’t strictly necessary for JavaScript development, but you will find that many tools, tutorials, and books assume familiarity with the terminal. If you are new to terminal usage, you may want to read Appendix A before proceeding.

I also strongly recommend that you become familiar with Git, a popular open-source version-control system. In addition to providing a “safety net” for your work, allowing you to easily revert changes and see the history of your work, it is ubiquitous in open-source development and development teams. If you haven’t used version control before, I strongly recommend you use Git to track and version your source code as you go through this book: it will be great practice for you. There’s an introduction to Git in Appendix B.

Your Project Root

You’ll want to create a directory for each project. We’ll call this directory the project root. For example, if you’re following along with the examples in this book, you could create an lj directory, which would be your project root (you could also create a directory or subdirectory for each chapter, and think of that as the project root—it’s up to you). In all the command-line examples in this book, we’ll assume that you’re in the project root. If you try an example and it doesn’t work, the first thing to verify is that you’re in the project root. Any files we create will be relative to the project root. For example, if your project root is /home/sam/work/lj, and we ask you to create a file public/js/test.js, the full path to that file should be /home/sam/work/lj/public/js/test.js.

What Are You Trying to Do?

One of JavaScript’s strengths is its flexibility: it can be used to write applications for the browser, server, mobile device, desktop, or even embedded devices. It’s beyond the scope of this book to explain every platform JavaScript might be used on, so we’re going to focus on its use in the browser and in Node (which runs on your computer or on a server). Happily, most other platforms are variations of these two cases (for example, if you want to build a desktop app, you might use Electron, which actually packages a browser application with a Node backend and makes it appear to be a desktop app).

If you don’t know yet what platform you need to target, just pick the one that seems the most interesting to you. If you want to make pretty things, a browser application is a good place to start, and if you’re interested in crunching numbers or processing data, Node is a better choice.

We’re going to start this chapter by covering Node development. Even if you’re primarily interested in web development, I recommend you read this section, since many web development tools, libraries, and frameworks use (or at least assume some familiarity with) Node and npm. Also, most nontrivial web applications rely on a “backend” running on a server or in the cloud—understanding Node will give you a more comprehensive picture of how web applications interact with the backend.

Tip

Like most languages, JavaScript changes over time. All of the material in this book will run in an up-to-date browser, or Node 8 or greater. However, you may read elsewhere about new language features, and want to try them out. To help JavaScript programmers know what features are available in what environment, New York–based developer kangax maintains an excellent compatibility table of ES6 (and ES7) features.

Node Applications

Every language requires a program to process your code so that a computer can understand it. For JavaScript, this program has traditionally been a browser. Node is simply another way to process JavaScript. While it lacks the multimedia capabilities of a browser, it can do things that a browser can’t, such as write files on your computer, or act as a server.

Installing Node

If you haven’t installed Node already (or are using a version prior to 8.11), go to the Node.js home page, click on the “LTS” (long-term-support) version, and follow the installation instructions. Once you’ve installed Node, verify that it is functioning on your system. From the command line, do the following:

$ node -v
v8.11.2

Running JavaScript Programs with Node

We’ll create a sample program that uses some ES6 features, and see how to run it with Node. Create a file called demo.js:

'use strict';
const sentences = [
  { subject: 'JavaScript', verb: 'is', object: 'great' },
  { subject: 'Elephants', verb: 'are', object: 'large' },
];
// es6 feature: object destructuring
function say({ subject, verb, object }) {
  // es6 feature: template strings
  // note that quotes below are backticks (`), not single quotes (')
  console.log(`${subject} ${verb} ${object}`);
}
// es6 feature: for..of
for(let s of sentences) {
  say(s);
}

To run our sample program, just do the following:

$ node demo.js
JavaScript is great
Elephants are large

Package Management: npm

Understanding npm is not strictly necessary to JavaScript development, but it’s increasingly becoming the package management tool of choice. For Node development, it’s practically essential. Whether you’re writing Node apps or doing browser development, you’ll find that life is a lot easier with npm.

Npm comes bundled with Node. To verify that it’s installed correctly, type:

$ npm -v
6.1.0

Your version numbers may vary as Node and npm are updated. Broadly speaking, npm manages installed packages. A package can be anything from a full application, to sample code, to a module or library that you’ll use in your project.

npm supports installing packages at two levels: globally and locally. Global packages are usually command-line tools that you’ll use in the development process. Local packages are project-specific. Installing a package is done with the npm install command. Let’s install the popular Underscore package to see how it works. In your project root, run the following:

$ npm install underscore
[email protected] node_modulesunderscore

npm is telling you that it installed the latest version of Underscore (1.9.1 as I write this; yours will probably be different). Underscore is a module with no dependencies, so the output from npm is very brief; for some complex modules, you may see pages of text go by! If we wanted to install a specific version of Underscore, we can specify the version number explicitly:

$ npm install [email protected]
[email protected] node_modulesunderscore

So where did this module actually get installed? If you look in your directory, you’ll see a new subdirectory called node_modules; any local modules you install will go in this directory. Go ahead and delete the node_modules directory; we’ll be re-creating it in a moment.

As you install modules, you’ll want to keep track of them somehow; the modules you install (and use) are called dependencies of your project. As your project matures, you’ll want a concise way to know what packages your project depends on, and npm does this with a file called package.json. You don’t have to create this file yourself: you can run npm init, and interactively answer some questions (you can simply press Enter for each question and accept the defaults; you can always edit the file and change your answers later). Go ahead and do this now, and take a look at the generated package.json file:

$ npm init

Dependencies are split into regular dependencies and dev dependencies. Dev dependencies are packages that your app can run without, but are helpful or necessary in building your project (we’ll see examples of these soon). By default, packages are installed as regular dependencies; if you want to install a dev dependency, use the --save-dev flag. Let’s go ahead and reinstall Underscore as a regular dependency:

$ npm install underscore
npm WARN package.json [email protected] No description
npm WARN package.json [email protected] No repository field.
[email protected] node_modulesunderscore

You might be wondering what all of these warnings are. npm is telling you that there are some components missing from your package. For the purposes of this book, you can ignore these warnings: you only need to worry about them if you’re using npm to publish your own packages, which is beyond the scope of this book.

Now if you look at your package.json file, you’ll see that Underscore is listed as a dependency. The idea of dependency management is that the dependency versions referenced in package.json are all that’s necessary to re-create (download and install) the dependencies themselves. Let’s try this out. Delete the node_modules directory again, and then run npm install (note we don’t specify any particular package name). npm will install any packages listed in the package.json file. You can look at the newly created node_modules directory to verify this.

Now that we’ve gone to all the trouble to install Underscore, we might as well see it in action. Modify demo.js:

'use strict';
const _ = require('underscore')

const sentences = [
  { subject: 'JavaScript', verb: 'is', object: 'great' },
  { subject: 'Elephants', verb: 'are', object: 'large' },
];

const verbs = _.pluck(sentences, 'verb')
for(let verb of verbs) {
  console.log(`found verb: ${verb}`)
}

We’re using require to to assign Underscore, cleverly, to an underscore. Then we can use Underscore’s “pluck” method to get the verb out of our sentences. Chapter 19 contains a more comprehensive overview of Node and packages. For now, you have everything you need to run the examples in this book using Node.

Web Applications

Unlike Node development, writing web applications carries an additional complication: you don’t control the client. The JavaScript you write may be run on an up-to-date browser, or something older. The JavaScript features available to you may differ from browser to browser. And each browser may have its own quirks, further complicating matters.

The good news for the aspiring web app developer is twofold. First, browsers have gotten much better in recent years, and “evergreen” browsers (browsers that automatically keep themselves up-to-date instead of relying on the user to upgrade them) have become the norm. Secondly, most popular frontend frameworks run your code through a transcompiler, which transforms the code you write into code that is likely to run on any browser.

As I write this, the most popular frontend frameworks are React, Angular 2, and Vue. Each of these frameworks has a utility that creates a skeleton (or “scaffold”) application on which you can base your own application. Certainly you can write web applications without using one of these utilities, or even without a framework at all. However, these all exist for a reason, and building a sophisticated, modern web application from scratch is not for the faint of heart!

For the purposes of this book—and learning JavaScript—you won’t need to use or learn one of these frameworks. But if your objective is web development, I recommend that you pick one and learn it as soon as you feel you have a basic grasp of the language.

You can find free introductory tutorials for these three frameworks here:

You don’t need a frontend framework to follow along with any of the examples in this book; you can just use an HTML file with a linked JavaScript file as we did in the first chapter:

index.html:

<!doctype html>
<html>
  <head>
    <title>My JavaScript Scratchpad</title>
  </head>
  <body>
    <h1>My JavaScript Scratchpad</h1>
    <script src="main.js"></script>
  </body>
</html>

You can put whatever you like between the <title> and <h1> tags, and you’re welcome to name the file something other than main.js. In your JavaScript file, you can write whatever JavaScript you want. Most of the examples in this book rely on console.log for output, meaning that you won’t see any changes unless you open your browser’s console (in Chapter 18, you’ll learn how to modify the web page itself). Try putting the following example (which gives you a random hand of cards from a fair deck) in main.js:

'use strict';
function draw(n) {
  if(n < 1 || n > 52) throw new Error('you must draw between 1 and 52 cards!');
  const deck = []
  for(let suit of ['u2660', 'u2663', 'u2665', 'u2666']) {
    for(let rank of 'A,2,3,4,5,6,7,8,9,10,J,Q,K'.split(',')) {
      deck.push(`${rank}${suit}`);
    }
  }
  const hand = [];
  while(n) {
    hand.push(deck.splice(Math.floor(Math.random() * deck.length), 1)[0]);
    n--;
  }
  return hand;
}
console.log("Your hand:");
console.log(draw(5));

If you open your browser console, you should see a random hand! You can even interact with your program; if you type draw(5) in the console, you’ll get a new hand of 5 cards. Note that the “deck” resets every time; after you read Chapter 9, you are encouraged to revisit this exercise and figure out how to make a more useful deck.

The funny codes ('u2660', etc.) are Unicode code points for card suits; you’ll learn more about Unicode in Chapter 3.

Linting

Do you run a lint roller over your dress or suit before you go to a fancy party or an interview? Of course you do: you want to look your best. Likewise, you can lint your code to make it (and by extension, you) look its best. A linter takes a critical eye to your code and lets you know when you’re making common mistakes. I’ve been writing software for 25 years, and a good linter will still find mistakes in my code before I do. For the beginner, it’s an invaluable tool that can save you a lot of frustration.

There are several JavaScript linters out there, but my preference is Nicholas Zakas’s ESLint. We’ll start by installing ESLint globally:

npm install -g eslint

Before we start using ESLint, we need to create an .eslintrc.js configuration file for our project. Each project you work on may have different technologies or standards, and the .eslintrc.js allows ESLint to lint your code accordingly.

The easiest way to create an .eslintrc.js file is to run eslint --init, which will interactively ask you some questions and create a default file for you.

In your project root, run eslint --init. The first question you’ll be asked is if you want to establish a style by answering questions, using a popular style guide, or inspecting your existing JavaScript files. If you choose to answer questions, you’ll have to answer the following (these questions may change in the future):

  • Are you using ECMAScript 6 features? Yes.

  • Are you using ES6 modules? Yes.

  • Where will your code run (Node or in the browser)? Choose the appropriate answer for your project.

  • Do you use CommonJS? No. (CommonJS is an alternative to ES6-style modules, which we won’t be using in this book.)

  • Do you want to use JSX? No. (JSX is a XML-based extension to JavaScript that is used primarily in Facebook’s React UI library. We won’t be using it in this book.)

  • What style of indentation do you use? A recent StackOverflow poll showed that the majority of programmers prefer tabs, but that more experienced programmers prefer spaces. I will let you choose your own path here….

  • What quotes do you use for strings? It doesn’t matter what you answer here…we want to be able to use either equally.

  • What line endings do you use (Unix or Windows)? If you’re on Linux or macOS, choose Unix. If you’re on Windows, choose Windows.

  • Do you require semicolons? This is a matter of personal preference. The examples in this book use semicolons, but you may choose to omit them.

  • What format do you want your config file to be in (JavaScript, YAML, or JSON)? Choose JavaScript (YAML is a popular data serialization format like JSON; choosing JavaScript means you don’t have to use quotation marks on property keys, which means less typing.)

After you’ve answered all the questions, you will have a .eslintrc.js file, and we can start using ESLint.

There are several ways to run ESLint. You can integrate ESLint with your editor, which is great, but the instructions differ for every editor and operating system: if you want editor integration, I recommend Googling the name of your editor with “eslint” and following instructions. You can also run ESLint directly on your source files. For example, to run it on demo.js, simply type:

$ eslint demo.js

You’ll see output that looks like this (depending on your configuration and the file you choose, the output will be different):

/home/ethan/lj/es6/demo.js
  4:59  error  Unexpected trailing comma     comma-dangle
  9:5   error  Unexpected console statement  no-console

✖ 2 problems (2 errors, 0 warnings)

There’s a lot of room for personal preference, and you don’t always have to heed ESLint’s preferences. When you see an ESLint error, you have two options: you can decide that you agree with ESLint’s suggestion and fix your code, or you can disagree with ESLint’s preference and change or disable the rule.

For example, I like trailing commas, so in this example, I wish to disable ESLint’s comma-dangle rule. If you’re confused about what a rule means, you can go to the ESLint homepage and search for the error code (comma-dangle in this case) for more information.

If you disagree with ESLint’s preference, edit the rule in the .eslintrc.js file. Each rule in the .eslintrc.js is an array. The first element is a string or number, where "off" (or 0) turns the rule off, "warn" (or 1) considers it a warning, and "error" (or 2) considers it an error. In my example, I checked the documentation for comma-dangle, and edited my .eslintrc.js file like this:

module.exports = {
   "rules": {
       /* changed comma-dangle default...ironically,
          we can't use a dangling comma here because
          this is a JSON file. */
       "comma-dangle": [
          "error",
          "always-multiline"
       ],
      "indent": [
         "error",
         4
      ],
      /* ... */

You’ll probably see an error referring to using console.log, which is generally considered “sloppy” (even dangerous if you’re targeting legacy browsers) when used in production browser code. For learning purposes, however, you can disable this, as we’ll be using console.log throughout this book. Also, you will probably want to turn off the "quotes" rule. I’ll leave it as a reader’s exercise to disable these rules.

Conclusion

In this chapter, we’ve learned how to set up basic Node and browser projects, run, and lint our code…now it’s time to learn some JavaScript!

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

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