Preparations

Getting started with JavaScript is easy. You can jump into your browser console and start writing JavaScript right now! However, a bit of preparation goes a long way, and learning some background should make your JavaScript journey a rewarding and productive experience. In this chapter, we'll show you how to run JavaScript, determine what the community coding conventions are, and where to go for help and documentation.

Runtime Environments

Depending on the problem domain and environment, applications must access various resources provided by the machine, such as networking infrastructure, RAM, sensors, and the GPU to do useful work. A runtime environment is an execution environment that lets an application program access system resources and provides the tools the application needs to operate.

In some cases, these tools let the application interact with the outside world. In others, they let the operating system interpret and understand what the application is doing. In other words, the runtime environment turns an application from a set of instructions into something that performs actual work.

The following is background information. You do not need to memorize it.

The phrase programming language is a fuzzy term that refers to a variety of different ways to tell a computer what to do. In a strict sense, a programming language is a set of syntactic and semantic rules that describe a formal language and must be able to express the steps that a machine needs to perform to convert some input to an output.

Before the computer can perform those steps, though, the program needs to be converted to a form the computer can understand. Programs called compilers and interpreters perform this conversion. At their most basic level, compilers and interpreters are similar: they both translate a program written in a specific programming language to something that the computer can execute, typically referred to as "1s and 0s" since all information on digital computers gets stored as 1s and 0s.

Compilers and interpreters differ primarily in what they do with those 1s and 0s. Compilers produce an output file that the computer can run directly, perhaps after some additional processing called linking. Interpreters, however, don't produce 1s and 0s that the computer can run directly - instead, the interpreter runs the interpreted code directly, or perhaps passes it on to a companion program.

JavaScript, at its heart, is an interpreted language. However, for performance reasons, most modern JavaScript engines employ a special kind of compiler called a Just In Time (JIT) compiler that takes the interpreted code one step further and lets the computer run the result.

For our purposes, this distinction between compilers and interpreters is unimportant. However, you'll encounter both terms in your career, and should generally have some sort of idea of whether you're working with a compiled or interpreted language, even if you don't fully understand the mechanics and ramifications.

When an application accesses an operating system's resources, something must ensure that the operating system provides them in a regulated and safe manner. An Application Programming Interface (API) provides that functionality: it describes the scheme and format that a programmer can use to securely access resources, with the operating system acting as an intermediary. A runtime environment typically adds another layer of abstraction on top of the operating system's API to make these resources available with a higher-level (i.e., more accessible) API. The compiler/interpreter and the operating system's APIs together make up a runtime environment. In other words, they provide the tools that an application needs to run. The APIs needed for one runtime environment can differ from those needed in another environment.

Besides access to a computer's resources, an application programmer also needs tools for debugging and profiling her code to find and fix bugs in her program. When you add these developer tools to the mix, you get a development environment. For our purposes, we'll treat the developer tools as part of the runtime environment.

In the JavaScript world, there are two major runtime environments you are likely to encounter: the browser and Node.js. You may also encounter a number of less common environments. Let's take a look at the major JavaScript runtime environments.

Browser

The web browser was the original JavaScript runtime environment, and it's still the most dominant. JavaScript running in the browser is far more ubiquitous than JavaScript running anywhere else. Almost every browser has a JavaScript engine built into it.

JavaScript in the browser has two main purposes: 1) to programmatically alter web pages based on user actions; and, 2) to exchange messages with a server over a network. To perform the first task, the programmer needs an API through which they can manipulate the structure and appearance of the HTML page. For the second task, they need an API that lets them use the operating system's ability to send and receive messages over a network. Almost every browser provides a way to accomplish these tasks, though there are some compatibility issues between browsers. The DOM (Document Object Model) API lets you manipulate the structure and appearance of a web page, while the XHR (XMLHttpRequest) interface and the Fetch API let you communicate with a server.

Runtime environments must provide tools that let developers debug and inspect programs. Browsers are no different. All major browsers provide a "Developer Tools" feature that includes a REPL, a debugger, a network inspector, a performance profiler, and more.

Node.js

As mentioned in the previous chapter, Node.js is a runtime environment that turns JavaScript into a general-purpose programming language that can run applications on almost any system. The creators of Node.js took the open-source Chrome V8 JavaScript engine and added APIs and tools required for desktop and server computing.

A general-purpose programming environment, like Node.js, needs the following minimal capabilities:

  • The ability to read and write disk files (disk I/O);
  • The ability to read and write via the terminal (standard I/O);
  • The ability to send and receive messages over a network (network I/O);
  • The ability to interact with a database.

Node.js has APIs and packages for all these tasks and more. It also provides an interactive REPL (read-eval-print loop) where you can execute JavaScript commands and get instant results. Like any useful runtime environment, Node.js provides tools for debugging and inspecting programs at runtime. Unfortunately, the debugging and inspecting tools are somewhat difficult to use directly; instead, you generally have to use a browser, and Google Chrome in particular. We will not discuss Node debugging in this book.

Other JavaScript Runtime Environments

Apart from browsers and Node.js, you can find JavaScript in some other environments. For example, Adobe's Acrobat supports JavaScript to automate and animate elements in a document. Other environments include ActionScript and GNOME shell. In this book, we'll limit our focus to the browser and Node.js runtime environments.

Installation

If you have a contemporary browser installed on your computer, you already have everything you need to run all the code in this book. However, you'll find that Node.js is more convenient than using your browser. With Node.js, you don't need to embed your JavaScript file in a webpage to run it; in a browser, you must load your JavaScript from an HTML file. We recommend Node.js version 12.0.0 or higher to work with the examples and exercises in this book. You can find official installation instructions for your platform on Node's website:

The quickest way to determine whether Node.js is installed is to try running it. Open your Terminal application, or the Windows Command Prompt if you're on Windows, and run the command:

$ node -v       # -v requests the version number
v12.4.1

Make sure this command displays version v12.0.0 or higher. In fact, we recommend installing the latest version of Node that you can.

The Node installation process should also install npm—Node's package dependency manager—for you, but it doesn't hurt to check:

$ npm -v        # -v requests the version number
6.5.0

If you can't or don't want to install Node.js on your computer, you can use web-based programming environments like repl.it to run the programs in this book. However, we recommend installing Node.js: it's a powerful and useful companion for learning JavaScript.

Using a Code Editor

Developers often use a code editor to write code. A code editor creates plain text documents with no styling or formatting. If you already have a favorite code editor (e.g., Visual Studio Code, Vim, Emacs, etc.), use it to work through this book.

If you do not have a preferred code editor, we strongly recommend using Visual Studio Code (also known as VSCode). It's free and built as an open-source project. It's highly polished and pleasant to look at and use. Most surprisingly, perhaps, is that it comes from Microsoft. Its popularity is skyrocketing in the developer community.

VSCode comes in Mac, Windows, and Linux versions.

Do not use a word processor when writing code. Word processors are for writing, not coding. They often inject invisible characters or whitespace into the document to help format and style it. While that can make your prose look great, it doesn't work well with code. Code written with a word processor may not run even if you copy and paste it into a code editor before saving it.

Stylish JavaScript

The JavaScript community has some stylistic guidelines that help make JavaScript code easier to read and write. Not all of the guidelines agree on all points, but there's plenty of overlap. Adhering to the style conventions of a programming language is helpful and meaningful even if you don't agree with every convention. You probably won't be the sole person developing and maintaining a software project; adhering to a particular style convention helps your teammates and future maintainers understand your code. It's hard enough to understand code written by someone else; don't make it harder with unusual or non-standard stylistic choices.

The conventions we'll talk about in this section are specific to the JavaScript community. Other programming languages—and even some JavaScript sub-communities—may have different preferences about each guideline.

Here's a short list of guidelines that we recommend. If you already work with a formal set of guidelines, please feel free to use them. If you don't, our suggestions should help you write readable code.

  • Set your text editor to use space characters—not tabs—for indentation. The editor should also insert spaces if you press the "tab" key on your keyboard.

  • Set your text editor to use 2 spaces for indentation and when converting tab characters to spaces.

  • Try to limit lines to 80 characters. This limit isn't a universal preference, but it helps readability. Not all developers have massive screens or good eyesight.

  • JavaScript uses the character sequence // to mark the beginning of a comment. Such comments run through the end of the line.

    let answerToUltimateQuestion = 42; // initializing a variable
    let aRoundNumber = 3.141592;       // another comment
    

    You can also use /* and */ for multiline comments and when you want to embed comments in the middle of a line:

    /* This is a multi-line comment.
       It can span any number of lines.
       The command ends when you see
       an * followed by a / as shown
       here ==> */
    
    // You can also use /* and */ to embed comments in the middle of a line:
    let area = w /* width */ * h /* height */;
    // You should avoid embedded comments
    

    Programmers use comments to leave notes for other programmers or themselves at a later point in time; however, don't overdo your comments. Let your code do the talking instead.

  • When writing a code block or function body with curly braces, write the opening brace on the same line as the function name or conditional expression. Use a single space just before the opening brace:

    if (isOk()){              // bad
      // do something
    }
    
    if (isOk())               // bad
    {
      // do something
    }
    
    if (isOk()) {             // good
      // do something
    }
    
  • Use spaces between operators and operands to make your code less cluttered and easier to read:

    let sum=x+5;              // bad
    let sum = x + 5;          // good
    
  • Use semicolons to terminate each logical line of code unless the line ends with {, }, or :. See the next section for details.

That covers the essential style conventions that you need to get started. If you want more information about JavaScript styling, we recommend Airbnb's JavaScript style guide. Check it out, but don't try to memorize all of the rules right away.

Naming Conventions

Naming conventions are similar to style conventions (and are often discussed together), but JavaScript naming conventions have more gray areas and complexity than most languages, so we'll discuss them separately.

  • Use camelCase formatting for most variable and function names. Such names begin with a lowercase letter. If the name contains multiple words, each subsequent word should begin with an uppercase letter:

    let answerToUltimateQuestion = 42;     // initializing a variable
    function fourScoreAndSevenYearsAgo() { // defining a function
      // do something
    }
    
  • Some function names -- constructor functions -- should normally use PascalCase (also known as CamelCase -- with a capital C) names. For instance:

    function DomesticCat(name) {           // defining a function
      // do something
    }
    

    We discuss constructors briefly a little later.

  • Use uppercase names with underscores (SCREAMING_SNAKE_CASE) to represent constants that serve as unchanging configuration values in your program.

    const INTEREST_RATE = 0.0525;
    const COURSE_NUMBER = 'JS101';
    const HOST = 'launchschool.com';
    const FIRST_LETTER = 'a';             // magic number
    const LAST_LETTER = 'z';              //
    

    We also use SCREAMING_SNAKE_CASE for constants that represent so-called magic numbers (which may not actually be numbers) -- constants that are important to your program in some way but not as configuration values. For instance:

    const SECONDS_PER_MINUTE = 60;
    const OUNCES_PER_POUND = 16;
    const METERS_PER_KILOMETER = 1000;
    const PI = 3.141592;
    const INPUT_PROMPT = '==>';
    const TODAY = new Date();
    

    Constants used to store functions (a feature we'll learn about later) should follow the same rules as function names: use camelCase for most functions, and PascalCase for constructor functions.

    const sayHi = function() {
      console.log("Hi!");
    };
    
    const Pet = function(name) {
      this.name = name;
    };
    

    For all other constants, the rules are much more flexible. You may use camelCase, PascalCase, or even SCREAMING_SNAKE_CASE. Use your personal preferences and any guidelines laid out by your teammates to choose your style.

    const greetings = `Hi! How are you today?`;
    const DeleteAllTodoLists = "DELETE FROM todolists";
    const FIND_TODOLIST = `SELECT * FROM todolists WHERE id = ${id}`;
    

All names -- variables and constants as well as functions -- should use the alphabetic and numeric characters only, though SCREAMING_SNAKE_CASE names may use underscores as well. The first character must be alphabetic. Do not use consecutive underscores nor should you use names with underscores at the start or end of the name.

On Semicolons

When you read JavaScript documentation, books, and articles, most show code that uses semicolons (;) to terminate most statements and expressions, so code ends up looking like this:

let x = 3;
let y = 5;

if (x === y) {
  console.log("x is equal to y");
} else {
  console.log("x is not equal to y");
}

As you can see, most lines end with a semicolon; there are exceptions like blank lines and lines that end with { or } and a few other situations. Most JavaScript developers use this style. You should, too, at least while you're at Launch School. At first, it's a bit tricky trying to decide whether you need a semicolon, but JavaScript is forgiving. The style becomes so automatic after a short period that you may find yourself typing semicolons everywhere you write something.

A few sources omit the semicolons entirely:

let x = 3
let y = 5

if (x === y) {
  console.log("x is equal to y")
} else {
  console.log("x is not equal to y")
}

A little-known fact is that JavaScript automatically, but invisibly, inserts semicolons where it needs them. Thus, you can omit semicolons from most code. Some experienced developers take advantage of this mechanism and use (and promote) a no-semicolons-ever style. However, the style requires care: the insertion mechanism makes mistakes when it sees your code differently than you intended. That can be tricky to diagnose when it inserts a semicolon where you don't expect or want one. Thus, we discourage using the no-semicolons style in our courses.

The main reason we mention this at all is that we use two different styles to display JavaScript code in this book: traditional and REPL style. Since the REPL style omits semicolons, it's worth knowing why we can do that.

In traditional style, we show the code as you would enter it in a file before running it. There is no special markup to show prompts, return values, or outputs. In this style, we use semicolons consistently. If we need to show some return values or outputs, we'll use comments:

function greeting() {
  console.log('Get ready!');
}

greeting(); // => Get ready!

In REPL style, we show code in a way that resembles a Node REPL session or a session in your browser console. A > prompt precedes each statement or expression that we expect you to type. We also precede return values with an = to distinguish them from console outputs that have no prefix at all. Note: don't type the > when entering commands and node doesn't display the =.

> greeting()
Get ready!   // console output
= undefined  // return value of greeting();

> 2 + 2
= 4          // return value of 2 + 2

Of particular note with REPL style is that we almost never use semicolons. You can type the semicolons if you want, but you don't have to. For the most part, the work you do in a REPL or console session probably won't lead to semicolon insertion issues.

The Command Line

This section discusses the commands that you need to run and test JavaScript code from the command line. It's by no means exhaustive, but it's enough to get you started. In particular, we'll take a quick peek at Node's interactive coding environment, the Node REPL, which is where you can test JavaScript code snippets in the terminal.

Note to Windows Users: The commands we show below may not work from Windows' default command prompt. We recommend that all Windows developers get familiar with a terminal emulator or with Powershell and issue these commands in that environment.

Command Line Commands

We assume that you know how to find the command line on your computer and enter commands. When you see the $ symbol in our code examples, it represents the command line prompt. The prompt may look different on your computer, which is fine; it varies depending on the machine you are working on and your local configuration. Note: don't type the prompt when entering commands.

We'll also refer to the command line as the terminal ("type in your terminal"), and we may sometimes talk about the terminal as the command line ("print to the command line"). The intent is generally clear from context.

Let's walk through some simple commands. Note that lines that begin with # are comments; you don't have to enter them.

# Create a folder named new_dir
mkdir new_dir

# Navigate into the new_dir folder
cd new_dir

# Create a file named new_file.js
touch new_file.js

# Delete the new_file.js file
rm new_file.js

# Navigate out of the current folder to the one above it
cd ..

# Delete the new_dir folder
rmdir new_dir

You can remove the directory and file at the same time with rm -R. Let's repeat the above steps, but this time we'll delete new_dir and the file simultaneously.

# Create a folder named new_dir
mkdir new_dir

# Navigate into the new_dir folder
cd new_dir

# Create a file called new_file.js
touch new_file.js

# Navigate out of the current folder to the one above it
cd ..

# Delete the new_dir folder and the file new_file.js
rm -R new_dir

Use extreme caution with the rm command. It's destructive and has no built-in way to recover from deleted files. It takes as much effort to wipe out thousands of files and directories with rm as it takes to delete a single file. If in doubt, use your file navigation program (e.g., Explorer or Finder) and delete files and folders that way; it's slower but safer.

That's all the commands you'll need in this book. If you want to gain more comfort and experience with the command line, many books and online tutorials go into far more depth. We recommend our book, Introduction to the Command Line, for beginners.

The Node REPL

A REPL (read-eval-print loop) for a programming language is an interactive environment where you can type commands and expressions in that language and get immediate results. Node.js comes with one such REPL, which you access with the node command:

node

This command produces a minimalist prompt:

>

The prompt tells you that you've entered the Node REPL. You can run JavaScript commands and see their outputs and return values from this prompt. For example, type the expression console.log('Hello, world!') after the prompt and press your Return or Enter key:

> console.log('Hello, world!')
Hello, world!
= undefined

This code prints the phrase 'Hello, world!' to the screen and returns a value of undefined. Note that you won't see the = in node's output: that's the stylistic convention we use to identify return values. node itself shows return values with a lighter or dimmer appearance.

We'll discuss return values later. All you need to know right now is that you can and should test code in node. With the REPL, it's easy to confirm whether some code works as you expect, and it can help you figure out how to fix the command if it doesn't work. The Node REPL is a great place to learn and practice!

When you want to exit the console and go back to the command line, press "control-c" twice, or press "control-d" once.

Running JavaScript

Running JavaScript files from the command line

Once you create a JavaScript file, one with a .js extension, you can run the code in that file by typing the node command followed by the file name. For instance, to run the code from a file named example.js, run this command from the command line:

node example.js

Let's try it. First, create an example.js file. You can create this file using your code editor (File -> New File) or you can run this command:

touch example.js

Using your code editor, write this code within your example.js file:

console.log('Hello, world!');

Now, run it:

$ node example.js
Hello, world!

When you run a JavaScript file from the command line, the code gets executed by something called an interpreter. You don't need to know much about the interpreter right now except that it takes JavaScript code and turns it into code that your computer understands.

The last tip is how to stop a running program. Sometimes, you'll have a long-running JavaScript program or an error in the logic that results in an infinite loop. To exit the program, use "control + c". This keystroke sends an abort signal to the running program.

Running JavaScript in the Browser

Any desktop browser can run the JavaScript examples we show in this book. We use Google Chrome since it has excellent developer tools and gets updated frequently, but you can use any browser you like. Chrome's frequent updates mean that you can experiment with new JavaScript features before they become widely available. As with most browsers, Chrome also supplies a REPL and supports running JavaScript from files.

Running code from a file in a browser is more complicated than running it from the command line. To do so, you must first embed the code in an HTML file. You can do this by following these steps:

  1. Create an HTML file (e.g., running_javascript.html) with some HTML content. Don't worry if you don't know HTML yet; you can use the following:

    <!DOCTYPE html>
    <html>
      <head>
        <title>Document</title>
      </head>
      <body>
      </body>
    </html>
    
  2. Add a script tag to the HTML file that has the path to your .js file in the src attribute:

    <!DOCTYPE html>
    <html>
      <head>
        <title>Document</title>
      </head>
      <body>
        #highlight
        <script src="example.js"></script>
        #endhighlight
      </body>
    </html>
    
  3. Save the HTML file, then open it in a browser. (Most browsers let you open an HTML file from the File, Open File menu.) Voila! Your code executes when the browser loads the file. You should see a blank page in your browser. To see the JavaScript output, you must visit the console, which we'll describe in the next section.

Another, perhaps simpler, way to run JavaScript in the browser is to write all your JavaScript between the opening and closing <script> tags: don't use a .js file at all:

<!DOCTYPE html>
<html>
  <head>
    <title>Document</title>
  </head>
  <body>
    <script>
      console.log("Hello, world!");
    </script>
  </body>
</html>

However, this can get a bit messy if you have a lot of JavaScript code.

The Chrome Console

To access Chrome's interactive console, click the Chrome menu icon at the top right corner of the Chrome browser window. From there, select the "More tools" submenu, and then the "Developer Tools" option to open the "Developer Tools" panel. Once there, you can click on the "Console" tab to access the Chrome console.

Chrome more tools menu

The console has several uses in Chrome, but for now, the most interesting feature is that it is also a REPL: it works in a way that is similar to the Node REPL. You enter JavaScript statements and expressions, and it responds with the output and return value. The following image shows Chrome's console in the Developer Tools window after executing an expression:

chrome console

Documentation

As you begin your programming journey, one of the most important habits you should develop is reading documentation. JavaScript, like all popular programming languages, comes with a rich set of reusable code that you can use out-of-the-box. However, you must read the documentation to learn how to use the features provided by that code. Without the documentation, the only way for programmers to learn how to use these components is to read the source code directly.

JavaScript's documentation focuses on the available data types, and the operations you can perform on those types. You can think of these data types and operations as components that your program can reuse. For example, the String data type is a component that lets you create and manipulate text data. You don't need to know how JavaScript implements a string; what's important is that it's a built-in component that you can reuse. Similarly, the operation toUpperCase is an operation that you can perform on strings; it converts all characters in the string to uppercase. Again, you don't need to worry about how the machine transforms the string under the hood; you can trust that toUpperCase does what it should.

Some developers use the term API to refer to documentation. This usage may seem confusing since, as we know, API also refers to how applications talk to each other. While it's incorrect to misuse the term API in this manner, it's easy to tell what a person means when they do. If someone asks whether you've looked at the Array API, they want to know whether you've read the documentation for the Array type. If they instead ask you how to work with Twitter's API, they want to know whether you can tell them how to use Twitter's services from their program.

Typically, a programming environment provides two main types of reusable code to an application: 1) components and operations that are part of the core language, often collectively referred to as the standard library; and, 2) components and operations specific to a runtime environment. Since our focus is learning the essentials of the core JavaScript language, we can limit ourselves to the core language documentation.

The official documentation of JavaScript standards can be found at ECMA International. The standards documentations are broken out by edition number (scroll down to the Online Archives). For instance, the 6th Edition refers to the 5th major version of the JavaScript standard published in 2015. ECMAScript 2015, aka ES6, is listed as the 6th edition (June 2015). Yes, the year ends in 5 while the ES name ends in 6. At the time of this writing (2023), the current version is the 14th edition, aka ES14.

The standards documentation are dense and dry, and are not a particularly fun read. However, when you really need to know how JavaScript is supposed to work, the standards are where you need to look. You should bookmark the standards documents even if you don't expect to need them very often.

For a more accessible read, the Mozilla Developer Network (MDN) provides a wealth of documentation about JavaScript as provided by the major browsers and Node.js. You should bookmark MDN now. You will be referring to it often now and well into the future, and not just for JavaScript, but HTML, CSS, and browser APIs as well.

The MDN documentation is not always completely accurate. While it can be relied on in most cases, many people contribute to the documentation, and they sometimes introduce inaccuracies and ambiguity. If you find a conflict between what Launch School tells you about JavaScript and what MDN says, you should generally rely on what LS says. Feel free to ask questions if you have doubts.

Here's a screenshot of the MDN documentation for the String data type:

MDN documentation for string

There's a lot to see. Let's focus on the three most crucial items; we've circled them.

The above screenshot might not look exactly like the page you'll find if you look up MDN's String Constructor. Websites will change things like layout and information all the time, especially as the language itself changes. The crucial items that we're going to look at should still be there, including a header that shows the constructor's name as well as a list of property and method names somewhere in a sidebar.

Constructors and Type Names

In the first circle at the top, we see the word "String." That's the name of the constructor for the data type that the page describes. It isn't evident from this page, but constructor names use a variation of camelCase that begins with an uppercase letter, sometimes called CamelCase (with the first letter capitalized) or PascalCase. The RegExp data type provides a better example.

We discuss constructors in detail in our Object Oriented Programming materials. For now, think of constructors as factories that create values of a particular type. A constructor represents a blueprint for a data type with the same name. The String constructor, for example, is a factory that creates values of type string.

The documentation page for a constructor describes how you can use that constructor to create values. It also lists the operations you can perform on values of that type. The page in the screenshot describes the String data type and the various operations and properties you can use with strings. Don't worry about what these words mean: the takeaway is that the top heading refers to the constructor for the String data-type.

Method Name

In JavaScript, methods are functions that need a value that you can use to call the function. For instance, to call the toUpperCase() string method, you need a string to call it:

> 'xyzzy'.toUpperCase()

The MDN documentation shows two types of methods: instance methods and static methods. It uses the format Constructor.prototype.methodName() to refer to instance methods, and Constructor.methodName() for static methods. For example, the String type provides an instance method named String.prototype.charAt() and a static method named String.fromCharCode(). We'll see examples of how to call both method types in the Instance Methods vs. Static Methods example below.

Notice that instance methods have .prototype. as part of their name. We'll discuss prototypes in detail in our Object Oriented Programming materials. For now, it's enough to know that methods with .prototype. as part of their full name are instance methods.

How do you remember whether a method is an instance method or a static method? It's unfortunate, but there's no rule-of-thumb you can follow; you must consult the documentation. With practice, you'll learn which methods are which, but you'll never learn them all.

MDN uses a number of different icons next to the property and method names on the left side of the screen. As of this writing in late 2021, the following icons are the one you're most likely to encounter:

  • A trash can icon. This icon identifies deprecated items. A deprecated item may not work in future versions of the language, so you shouldn't use those items in new code.
  • A blue triangle icon with a ! in the middle. This icon identifies non-standard items. These items should not be used without understanding that they may not work on all platforms.
  • A beaker icon. This icon identifies experimental items. These items should not be used in production applications as the behavior may change or be removed at some time in the future.

At one time, MDN used a thumbs-down icon to identify deprecated items -- the image shown above uses the thumbs-down icon for deprecated items.

Once you've identified a method or property that you want to use, you can click on its name to open a new page with more information.

Property Name

As well as operations, some data types have properties associated with them. A verb vs. noun analogy is useful here. A data type's property is a noun; an operation is a verb. A property name says something about the value and an operation does something with that value.

One property of strings is the length, measured in characters. For example, "hello" has 5 characters, which means its length is 5. Note that the quotes are part of JavaScript syntax; they aren't part of the string's value, so they don't count in the length property.

You can access a property by appending a dot and the name of the property to that value:

> "hello".length
= 5

Example: Instance Methods vs. Static Methods

The big takeaway from this section—it's worth repeating—is that you apply instance methods to a value of the type that the constructor represents. Thus, we can apply an instance method to the string "Hello". For example, from the method list sidebar, we see the instance method, String.prototype.concat. That is, concat is a method that we can call on any string:

> 'Hello, '.concat('Bob!')
= 'Hello, Bob!'

The documentation also tells us that Strings have a static method named String.fromCharCode. To call a static method, you use the constructor name (String) instead of a value. For instance:

> String.fromCharCode(97)
= 'a'

As you can see, this method returns the character value of the UTF-16 code point, 97. More importantly, we didn't need a String to call it. Instead, we used the constructor to call the method.

Some materials say that fromCharCode's argument is an ASCII value. While that's technically incorrect, it's common enough that you should be aware of the usage. In practice, most of the characters you'll work with will be from the ASCII character set; the ASCII values of those characters are the same as the UTF-16 equivalents.

Searching for Documentation Online

The best way to search for JavaScript documentation is to precede your search term with the word "mdn". For example, if you want to look up documentation about JavaScript arrays, search for "mdn javascript arrays". Otherwise, you'll probably get results from inferior sources at the top of the search page.

Be careful when reading MDN. The documentation is "crowd sourced" in that nearly anybody can update it. Every so often, someone updates the content in such a way that is incorrect. For example, in July 2020, someone updated the documentation for the Array.prototype.filter method to incorrectly describe the method's callback function. Such discrepancies become especially important in assessments. If there is a conflict between the way we say something and the way MDN says it, you should use the Launch School wording. The Launch School wording is the one we'll use when grading assessments.

It's worth noting that the MDN documentation is not always helpful, even when you find the right page. You can search the web for a better explanation if necessary. Be careful, though: searches often turn up outdated or incorrect content, so focus on recent items and try to look at several pages for conflicting information. AI tools like ChatGPT may also be helpful, but be extra careful: AI tools may lie to you. Convincingly.

About the Exercises

A question that comes up often with our exercises is "My answer is different from Launch School's, but it still works. What should I do?"

Even with simple problems, there are often several different ways to solve an exercise, and sometimes many different ways. At this stage in your journey, important part is to understand what you’ve read and be able to do use that knowledge to answer questions, even if your answer is a little different. Once you're satisfied with your answer, you want to check it against Launch School's answer. Your answer doesn't have to be the same as ours. In fact, having an alternative answer affords you the opportunity to learn from seeing a different approach. How is your solution different from Launch School's? Do you understand our solution too?

Of course, you should be sure to check that your answer satisfies the requirements of the exercise. Does the output match the expected output, exactly? Does it properly handle any edge cases that may be mentioned? Sometimes, an answer may seem like it's correct, but you may have missed one of the requirements.

As long as you understand both your solution and ours, feel free to move on to the next exercise. At this point, you’re building up an awareness of the language, methods, and all the different ways you can do things. Having a different answer is not bad or a sign that you need to go back.

Exercises

  1. Create a directory named my_folder and navigate to that directory. Create two files named one.js and two.js in my_folder. Add the following JavaScript code to one.js:

    console.log("this is file one");
    

    Add some code to two.js that logs 'this is file two'.

    When you're finished, run both programs with node.

    Solution

    $ mkdir my_folder
    $ cd my_folder
    my_folder $ touch one.js
    my_folder $ touch two.js
    
    # use your editor to edit one.js and two.js
    
    my_folder $ node one.js
    this is file one
    
    my_folder $ node two.js
    this is file two
    

    Video Walkthrough

    Please register to play this video

  2. When you finish Exercise 1, navigate to the directory above the my_folder directory and delete all the content you generated in exercise 1 with one command.

    WARNING: The rm method is DANGEROUS. Once you run this command, there is no undoing it. It is permanent. Make sure you are in the correct directory and that you use the correct name of the directory you want to delete.

    Solution

    my_folder $ cd ../
    $ rm -R my_folder
    

    To repeat, make sure you use extreme caution when using the rm command. It's destructive and irreversibly deletes folders and files.

    Video Walkthrough

    Please register to play this video

  3. Create a file named foo.js in a directory named preparations_exercises. Add the following code to the file.

    let foo = "bar";
    console.log(foo);
    foo;
    

    Solution

    mkdir preparations_exercises
    cd preparations_exercises
    touch foo.js
    
    let foo = "bar";
    console.log(foo);
    foo;
    

    Video Walkthrough

    See Exercise 4 Solution

    1. Use node to run the foo.js file using node. What does it output?
    2. Copy and paste the code from foo.js into the node REPL. What does it output?
    3. Copy and paste the code from foo.js into the Chrome console REPL. What does it output?

    Solution

    $ node foo.js
    bar
    
    > let foo = 'bar'
    = undefined
    
    > console.log(foo);
    bar
    = undefined
    
    > foo
    = 'bar'
    
    > let foo = 'bar';
      console.log(foo);
      foo
    bar
    = "bar"
    

    The takeaway here is that variations in the output depend on how you run your code. The one feature all three environments have in common is that each logs the value bar to the console. Generally, a REPL has an output for every line of code. The Chrome console does not run the code one line at a time when you paste a multiline code snippet. That's why the output appears different when compared to the node REPL.

    Video Walkthrough

    Please register to play this video

  4. Identify the Constructors for each of the following methods and classify each method as either a "Static" or an "Instance" method:

    • substring
    • create
    • fromCharCode
    • slice
    • toString

    It might be that more than one constructor provides a method with a given name. Make sure you list them all in your answer. You can limit your search for methods to the String, Object, Array, and Number constructors.

    Use the documentation at Mozilla Developer Network (MDN) and Google to determine which constructors provide each method.

    Solution

    Method Name Constructor Method Type
    substring String Instance method
    create Object Static method
    fromCharCode String Static method
    slice Array, String Instance method
    toString String, Object, Array, Number Instance method

    Video Walkthrough

    Please register to play this video

  5. Which of the following names satisfy the style guidelines for variable names? For the purposes of this question, constants are not variables.

    Name
    index
    CatName
    snake_case
    lazyDog
    quick_Fox
    1stCharacter
    operand2
    BIG_NUMBER

    Solution

    Acceptable names: index, lazyDog, operand2

    Video Walkthrough

    Please register to play this video

  6. Which of the following names satisfy the style guidelines for function names?

    Name
    index
    CatName
    snake_case
    lazyDog
    quick_Fox
    1stCharacter
    operand2
    BIG_NUMBER

    Solution

    Acceptable names: index, lazyDog, operand2, CatName—variable names and function names generally have the same guidelines, but constructor functions can use PascalCase names like CatName.

    Video Walkthrough

    Please register to play this video

  7. Which of the following names satisfy the style guidelines for constants used to represent magic numbers?

    Name
    index
    CatName
    snake_case
    lazyDog
    quick_Fox
    1stCharacter
    operand2
    BIG_NUMBER

    Solution

    Acceptable names: BIG_NUMBER.

    Video Walkthrough

    Please register to play this video

  8. Which of the following names don't satisfy the style guidelines for naming variables, functions, or constants?

    Name
    index
    CatName
    snake_case
    lazyDog
    quick_Fox
    1stCharacter
    operand2
    BIG_NUMBER

    Solution

    Unacceptable names: snake_case and quick_Fox contain underscores; underscores are permitted in constant names, but these aren't constant names since they use lowercase letters. 1stCharacter isn't valid at all: names may not begin with a digit.

    Video Walkthrough

    Please register to play this video