6 JavaScript

6.1 What is JavaScript?

According to Wikipedia (emphasis mine):

JavaScript (/ˈdʒɑːvəˌskrɪpt/), often abbreviated as JS, is a high-level, just-in-time compiled, multi-paradigm programming language that conforms to the ECMAScript specification. JavaScript has curly-bracket syntax, dynamic typing, prototype-based object-orientation, and first-class functions.

Alongside HTML and CSS, JavaScript is one of the core technologies of the World Wide Web. JavaScript enables interactive web pages and is an essential part of web applications. The vast majority of websites use it, and major web browsers have a dedicated JavaScript engine to execute it.

Initially only implemented client-side in web browsers, JavaScript engines are now embedded in many other types of host software, including server-side in web servers and databases, and in non-web programs such as word processors and PDF software, and in runtime environments that make JavaScript available for writing mobile and desktop applications, including desktop widgets.

6.2 CodeCademy Lessons

Codecademy has a nice JavaScript tutorial that walks you through the features of JavaScript. It is devided into several lessons:

  1. Introduction (includes variable declaration)
  2. Conditionals
  3. Functions
  4. Blocks and Scope
  5. Arrays
  6. Loops
  7. Iterators
  8. Objects
  9. Classes
  10. Browser issues
  11. Modules
  12. Promises
  13. Async / await
  14. Requests

We will work our way through most or all of these during this course. Some will be assigned to do outside of class and some will be done (or at least started) in class.

6.3 Style Guide

6.3.1 Why style matters

Codying style is incredibly important. It makes code more readable and more reliable (by make errors easier to avoid and/or detect). Here are some style guide items that you are required to use in this course.2

6.3.2 Example Style Guides

Here are several “complete” style guides that attempt to cover every situation. Although they do not entirely agree with each other, they have many similarities. All of them have the goal of producing code that looks the same no matter who writes it.

If you want a more complete style guide, try one of these. But note that they may not be entirely consistent with each other or with the simplified style guide presented here.

Fortunately, we won’t need to know all of the details of these style guides. Instead, we will let the computer format our code for us. Specifically, we will use a tool called prettier, which can be added as a plug-in to many code editors.

Still, it is handy to have a simple style guide in mind when writing code.

6.3.3 A Simple Style Guide

What follows is not really a complete style guide, it only addresses the most important or most common features of a style guide.

  1. Be consistent.

    This is the most important rule. The rest of this style guide makes some choices that help with consistency (both within your own code and in code written by differnt people). Once in a while there may be a good reason to do things differently, but

    • Exceptions should be rare (and justified).
  2. Use the space bar!

    Using spaces appropriately is the single most important thing you can do to improve the readability of your code.

    • Always put spaces after commas.

    • Always put spaces around arithmetic operators (+, -, *, etc.), logical operators (&&, ||, etc.), and comparators (<, ==, ===, !=, etc.).

    • Always put spaces between comment markers (//, /*, */) and the text of the comment.

    • Use indentation to show logical structure of your code. (This is not forced like it is in Python, but use your good Python habits in JavaScript, too.)

    • Rarely: Use spaces to align parallel pieces of code.

      This seems like a really good idea at first, and it can make ceratain code easier to read. But when you go back and edit, the edits often break the formatting. At that point you either have ugly formatting or you need to do a bunch of additional edits to fix the formatting (which in turn makes the amount of change look larger than it really is to things like git and diff). So use this sparingly.

  3. Avoid long lines. (Nothing more than 80 characters.)

    Lines of code shold not be “wrapped”, you should decide where to break them. Typically lines of code should be limited to 80 or fewer characters.

    Choose your line breaks (and indendtaion) to improve code readability.

  4. Choose meaningful names that are not overly long.

    Exceptions:

    • one character names may be used in very short loops (but a longer name is often better).

    • D3 convention uses d and i for a data element and its index in many functions. Consistently following this makes your code clear.

  5. Use camelCase.

    Variable and function names in D3 tend to use camelCase – the initial letter is lower case and internal capitalization is used to subdivide multi-part names.

    Good: myVar, myLongerVarName, coolFunction()

    Bad: MyVar, my_longer_var_name, CoolFunction()

  1. Use arrow functions (mostly).

    JavaScript provides three ways to define functions. Simple anonymous functions are used widely in D3, and arrow functions make the notation for these terse and clear. So arrow notation will be our default notation for declaring functions.

  2. Declare variables with const (if possible) else with let.

    Older versions of JavaScript only had var for variable declaration. Recent versions have added let and const. Use const when the value of the variable should not change and let otherwise. (let keeps scoping more localized.) Only use var if let or const won’t do.

  3. Be consistent about semicolons.

    This is a tough one. The JavaScript community is divided on the use of semicolons.

    Semicolons in JavaScript are command separators, not command terminators. So they are only required when

    • putting multiple commands on one line,
    • to avoid certain ambiguities, which can generally be avoided by using good style.

    But to do this, you need to know a bit about how the JavaScript parser splits things up when semicolons are not present. Behind the scenes, JavaScript inserts semicolons

    1. when the next line starts with code that breaks the current one (ie, if it would not be possible to continue with what’s on the next line.)
    2. when the next line starts with a }, closing the current block
    3. when the end of the source code file is reached
    4. when there is return, break, throw, or continue is on a line by itself.

    So pick one and run with it: Either put them in manually yourself (everywhere) or leave them out (unless required to keep code from breaking). Don’t sprinkle them in here and there randomly. (Prettier allows you to decide which way it handles semi-colons.)

6.4 Prettier – automated code reformatting

Fortunately, much of this can be automated using prettier, a code reformatter.

6.4.1 Some options

Prettier doesn’t have many options. This is by intent. Fewer options means less time debating style and more time coding. Mostly, we will accept the default settings for prettier, but here a few things to check on.

6.4.1.1 Prettier config

  • semicolons: choose to use them always or only when required.

  • commas: JavaScript allows trailing commas in array and object specifications. You can force or forbid this optional commas. (The advantage of trailing commas is that if you delete the last line, you don’t also have to edit the second to last line to remove the comma.) Actually, you have some choice about where trailing commas are/are not used.

  • tabs: convert tabs to 2 spaces

  • quotes: prefer single or double quotes for strings. [Choose single – that seems to be more common in JS code.]

Prettier format options can be stored in a file named .prettierrc. Here is an example:

{
  "useTabs": false,
  "semi": false,
  "singleQuote": true,
  "trailingComma": "es5",
  "arrowParens": "avoid",
  "tabWidth": 2
}

Some editors (like VS Code) have provide an interface for configuring these settings. You can create a custom .prettierrc file using this online tool.

6.4.1.2 Editor options

You might also like to adjust some editor settings.

  • Format on save: Most editors have an option to reformat the code each time you save. It’s your choice whether you want this on or off.

  • Format as you type: Same goes for formatting as you type.

6.5 Resources


  1. I’ve talked to people in industry who say that not following the company style guide is a fireable offense. It is too costly to the company to have people writing code that doesn’t comply with company standards.