CHAPTER

JavaScript: The Language of the Web

TIME LIMIT: 5 hours

Fuck it, Ship it. - popular sticker at web programming conferences

JavaScript is the programming language that every browser interprets. This chapter discusses JavaScript’s history and the environments in which you can use it. We then use the JavaScript console to take a whirlwind tour of some of its programming features.

The Whims of History

The Internet and World Wide Web represent one of the greatest communications revolutions in human history. Like the Gutenberg printing press, the Internet is a culmination and amalgamation of centuries of scientific innovation.

Technically speaking, the Internet is the global system of computer networks that connect with one another using a specific Internet Protocol (“IP”). It is a network of networks, if you will. The World Wide Web is all of the resources that are hosted and connected together through the Internet.

The Web was a wild, wild place when it was first created. People needed help navigating the thousands of new resources. They needed a way to browse the web. On December 25, 1990, Tim Berners-Lee dropped the first web browser on the world. It was named WorldWideWeb.

By the mid-1990s, the Internet gold rush was on. The Internet and availability of personal computers had both hit critical mass, and the public was hungry for that sweet digital data. It was clear the Internet was the next big thing. There was green field to capture. Dammit, there were trillions of dollars to be made! Sir Tim Berners-Lee’s (he got knighted for creating the Internet) browser wasn’t going to cut it. The “Browser Wars” began.

The primary combatants in the capitalist war to be the primary browser of the web were Microsoft’s Internet Explorer and Netscape’s Navigator.

In the mid-90s, Microsoft could do whatever it wanted. Microsoft owned Windows, which was the overwhelmingly dominant operating system software of the day – a monopoly on consumer desktop systems. Internet Explorer was Microsoft’s browser, and it was bundled onto every consumer desktop with Windows. Everybody had an Internet Explorer application.

In an effort to compete on features, Netscape added a complete programming language to the Navigator browser. Netscape went so far as to create an entirely new language - JavaScript.

JavaScript was named JavaScript because Netscape wanted to market the language as “Java-like”. Java is what you would call an object-oriented programming language. However, the programmers working on JavaScript were actually making a language that worked a lot more like another programming language, Scheme, which a popular functional programming language. So JavaScript was originally the result of some pretty stilted decision-making and was kind of a piece of shit. Netscape shipped it, so web programmers used it. So we’re using it.

In polite company, you can condense the previous paragraph into one sentence – “JavaScript is a multi-paradigm programming language.”

In the end, Netscape’s marketing efforts came to naught. Monopoly Microsoft whipped their ass. Netscape sold themselves to America Online.

You've got mail!

However, JavaScript caught on and was implemented by other browsers. Navigator morphed into the open-source Mozilla/Firefox project we all know and ❤️ today.

How The Story Ends:

As the browser market wars continued, the developers suffered from the lack of a standard.

JavaScript’s standards were taken over by the standards body Ecma International, who have renamed the formal language specification “ECMAScript”. ECMAScript is currently on version 6 – people often refer to the new features as ES 6*. Unless they’re talking about the formal standard or new features, though, people still just generally call the language “JavaScript”.

Interpreters and Environments

In order to read the JavaScript language, a computer program (like a browser) needs a JavaScript interpreter. An interpreter is another program which takes JavaScript code as input, then converts it into the 0s and 1s that can run on your computer’s central processing unit microchip. The two primary JavaScript interpreters are V8 and Spidermonkey. Both are open-source.

Spidermonkey is the original JS interpreter from the Netscape days and is now used in Mozilla Firefox browser and various other projects like MongoDB and the GNOME desktop that many Linux distributions use. The V8 interpreter was developed by Google and is used in the Chrome browser and the Node.js project.

There are two basic environments: client-side and the server-side. In the world of JavaScript, web browsers are the main client-side applications using JavaScript. The Node.js environment allows you to run JavaScript scripts from the command-line. We will cover Node.js (and it’s npm package manager) in a later chapter.

Hello JavaScript programming language, Hello JavaScript Console

Most of work in this book so far has been client-side – HTML and CSS. We will stick with the client-side and now familiarize ourselves with the JavaScript console. As with all of the browser developer tools, I recommend investing in becoming comfortable with the JavaScript console – it will do nothing but make your life easier. It’s also your sandbox - play around with it.

Life's a beach.

Open a JavaScript console (it does not matter what webpage you are on) and follow along by typing out and experimenting with the code examples below. Pressing ENTER causes code to run. Pressing SHIFT-ENTER will drop your cursor into a newline.

The rest of this chapter is a tour through enough of the JavaScript programming language to make you dangerous. I am seeking to give you enough pieces of the language that you can start thinking about how to combine them in interesting ways.

This is one of the rare chapters where I want you to write code that you do not push to a GitHub repository (though you can if you want! Just name a file index.js and have at). Focus on the language and getting it to work in the developer console.

Hello, World.

Browser implementations of JavaScript come with a lot of built-in functionality for interacting with webpages (see API in the glossary). Let’s pop up an alert in the browser window. Type the following:

alert("Hello world!");

You can log things within the console:

console.log("This is how you log things.") // This is a comment, it does nothing.

The built-in console object actually has a lot of stuff you can do. You can examine it this way:

console.dir(console);

Click around. You’re not going to break anything.

For objects that aren’t built-in, like console, you can make them:

let famous_programmer = "Grace Hopper";
console.log(famous_programer); // evaluates to "Grace Hopper"

You can control the entire webpage from the JavaScript console. Want to overwrite the whole webpage? Just use the built-in document object. That object has a method called write.

document.write("<h1>HELLO WORLD</h1>");

There are lots of different ways to communicate with a user:

const name = prompt("What's your favorite Meetup?");
document.write("<h1>HELLO " + name.toUpperCase() + "</h1>");

Note the semicolons at the end of each statement. Semicolons are how you tell JavaScript that “Hey, this is a separate piece of code.”

While what we’ve been doing is exciting, all of this webpage interaction isn’t part of the formal JavaScript language. The browser makers added APIs like the document object to make developing webpages easier.

The rest of this chapter will talk about the formal JavaScript programming language. We will spend plenty of time exploring the browser environments and its built-in functionality in later chapters, though!

Primitive Data Types And Stuff You Can Do With Them

Time to think like a computer.

To a computer, everything is data. So programming languages have ways for you to express different kinds of common data. We call these data types.

In JavaScript, there are six primitive (simple) data types. Let’s review them. Along the way, we see how we can manipulate and use data using various features of the JavaScript language.

1. Number

When you console.log a primitive data type, the console merely spits the data type back at you.

666;
console.log(666);

Which makes sense.

typeof 666;  // should return "number".

Oh, how handy! We have a typeof operator. This particular operator tells us what type of data a value is.

typeof 5; // "number"

The more that you study programming languages, the more you will wind up reading about data types.

You can perform the standard addition, subtraction, multiplication, and division on Number types in JS. Each of these functions has its own operator:

4 + 5   // evaluates to 9
9 - 12  // evaluates to -3
6 / 9   // evaluates to 0.6666666666666666
3 * 2   // evaluates to 6

There is also a more exotic modulo operator - %. Modulo is really just a fancy word for a remainder in division.

8 % 6 // evaluates to 2
9 % 2 // evaluates to 1

Modulos often come in handy in job interviews.

As we saw above with typeof, JavaScript identifies every number you create is identified as a "number". JavaScript has a special built-in object called a Number:

console.dir(Number);

Click around.

2. String

Strings are the data type for textual data. It is data that you put in quotation marks. You can use “double”, ‘single’, or `back-tick` quotation marks. JavaScript doesn’t give a shit.

typeof "Give me two pina coladas.";
typeof 'One for each hand.';
typeof `Let's set sail with Captain Morgan`;

There is one special thing about the back-ticks, though - you can use it to create a “template literal”:

let name = "Mom";

console.log(`Hi, ${name}!`) // "Hi, Mom!"

let github_name = "kevmo";
console.log(`https://github.com/${github_name}`);

Template literals are ES 6.

There are a WHOLE BUNCH of string manipulation methods. You can see them on the String object (every string you create is an instance of this String class object):

console.dir(String);

Click around. Let’s try a few of these:

const language = "JavaScript";

language.toUpperCase();

language.replace("Script", "Soggy");

language.split("");

That last one created a more complex data structure known as an array.

Strangely enough, JavaScript lets you use the + operator with strings:

let name = "kev" + "mo";
console.log(name);

What happens if you try to add string and number values together?

typeof(2);  // "number"
typeof("pac"); // "string"

console.log(2 + "pac"); // "2pac"

let bestRapper = 2 + "pac";

typeof bestRapper; // "string"

Interesting! JavaScript took the 2 number and converted it to a string, in order to make the + operator work. This is called type coercion. JavaScript will do all sorts of weird things to try and make your code work. Awareness of type coercion is important for writing JavaScript. Interviewers often ask about it. You can find many articles about it online. There are a number of diagrams.

Because JavaScript is so willing to change data types, it is referred to as weakly typed (strongly typed languages would throw an error if you tried to use a + operator to combine a string and number).

3. Boolean

There are only two values - true and false - that qualify as a Boolean data type:

typeof true; // "boolean"
typeof false; // "boolean"

It is handy to have a set of binary values - they help you decide whether to do things. Let’s see how Booleans work with another JavaScript language construct, if statements (remember, you can use SHIFT-ENTER if you want to insert newlines, ENTER will just make the code run).

if (true) {
  console.log("Yes, this is true.")
};

if (false) {
  console.log("This will never run.")
}

There are a number of operators and built-in functions that will (basically) evaluate to true or false. For example:

3 > 2; // evaluates to true

3 < 2; // evaluates to false

3 === 3; // evaluates to true, because 3 is equal to itself

These sorts of evaluations are referred to as truthy and falsy. You can combine truthy and falsy statements with if statements to create branching programs. Look at the if-else statement below:

if (3 < 2) {
  console.log("This code will never run because (3 < 2) will always evaluate to false.");
} else {
  console.log("This code will always run instead.");
}

This ability to use this sort of conditional execution - to make some code blocks execute while skipping others - is called control flow.

4 and 5. null and undefined

In programming-speak, null and undefined both mean “there is no value here”.

typeof lololol; // evaluates to "undefined"

The value of lololol is undefined because lololol has not been designated as any sort of value in our program.

null and undefined evaluate as falsy statements.

if (null) {
  console.log("This code will never execute.");
} else if (undefined) {
  console.log("Neither will this.")
} else {
  console.log("This default text will print.")
}

Null and undefined are mostly interchangeable.

What do you think happens when you evaluate typeof null?

typeof null // "object"

What?

Welcome to JavaScript.

6. Symbols

Symbols are an ES6 feature. We do not cover them in this book, but there is plenty of information about them on the Mozilla Developer Network if you need it.

Object

JavaScript’s 7th, final, and only complex data type is the Object. Objects are JavaScript’s conceptual workhorse. Scratch beneath the surface of the syntax and you will often find that JavaScript is evaluating something as an object.

Objects are mappings of keys and values. They look like this:

{
  fullName: "Ralph Nader",
  yearBorn: 1929,
  party: "green",
  getAge: function(currentYear) {return currentYear - 1929}
}

In the object above, fullName, yearBorn, party, and getAge are the object’s keys, or properties. getAge is a special kind of property – because its value is a function, we call it a method.

One way to get at the information in an object is to bind it to a name:

 let ralph = {
   fullName: "Ralph Nader",
   yearBorn: 1934,
   party: "green",
   getAge: function(currentYear) {return currentYear - 1929}
 };

Now you can access the values on ralph using property names:

ralph.fullName; // evalutes to fullName
console.log(ralph.party + " party")l // logs "green Party"

Call the getAge method as follows:

ralph.getAge(2018); // evaluates to 84

You have to use parenthesis after a functon name to call the function. In the event that the function takes arguments or parameters (e.g. ralph.getAge takes one paramenter - currentYear).

If you forget to put a property on an object at its moment of creation, you can add properties later:

ralph.firstBook = "Unsafe At Any Speed";

console.log(ralph.FirstBook); // "Unsafe At Any Speed"

Objects are excellent data structures. You can stick as much data and and as many functions on an object as you want. They and arrays are JavaScript’s two most fundamental data structures.

We will now examine two special kinds of objects that have their own syntax - functions and arrays.

Functions

Functions are objects that are callable. You can wrap code inside of a function body, and then call it at will.

This is how you declare a function:

function logger(message) {
    let date = new Date(); // using the built-in Date object

    let logEntry = date.toLocaleString() + ": " + message;

    console.log(logEntry);
};

This is how you call it:

logger("Almost done with this chapter!");

// logs "9/18/2018, 8:20:28 AM: Almost done with this chapter!"

Functions are an indispensable part of any general-purpose programming language. They are one of the primary ways people re-use code, implementing the “Don’t Repeat Yourself” (DRY) principle.

Don’t forget: In JavaScript, functions are just objects that are callable. When you’re not calling them as functions, you can treat them the same as objects. For example, you can attach properties to functions just like any other object.

typeof logger // evalutes to "function"

logger.codeAuthor = "kevmo";

console.log(logger.codeAuthor); // logs "kevmo"

Having functions operate as standalone values like this is incredibly valuable. You can pass functions around the same way you do any other data type. We end with a final demonstration:

function add(x, y) {
  return x + y;
}

function addFive(x) {
  return add(5, x);
}

console.log(addFive(10)); // logs 15

All JavaScript programmers make heavy use of functions.

Arrays

The other special type of object is an array. While functions exist to add in code re-use, arrays exist as convenient data structure – they are ordered lists of data:

let programmers = ["Ada Lovelace", "Grace Hopper", "Kevin Moore"];

console.log(programmers);

Arrays come with plenty of built-in functionality:

console.log(programmers.length); // prints 3

programmers.forEach(console.log);

Arrays are zero-indexed – they start counting at 0 instead of 1:

console.log(programmers[0]);  // logs "Ada Lovelace"
console.log(programmers[2]);  // logs "Kevin Moore"
console.log(programmers[3]);  // logs undefined

You can easily loop across arrays:

for (let i=0; i < programmers.length; i = i + 1) {
  console.log(programmers[i]);
};  

For loops are very handy. You create them by handing the for a value to start at, a value to end at, and a formula for incrementing values. In pseudocode:

  for (initial value of i, stopping value of i, formula for changing i) {
    body of for loop that has i's value available
  }

Since you know that arrays start at 0 and stop 1 before their length, it is easy to create programming constructs that loop over all of the data objects in an array.

There are a number of ways to manipulate arrays:

programmers.pop(); // removes and returns "Kevin Moore"

programmers.length; // is now 2

programmers.push("Bill Israel");

programmers.length; // back to 3

Given that arrays are one of the primary ways you store groupings of data in JavaScript, you will be gaining ample experience with them throughout the rest of Part 4.

Variables (Bindings)

You keep seeing let someNameOrAnother = DATA VALUE be used to assign names to strings, numbers, objects, functions, etc. The someNameOrAnother part of this code is called a variable. Variables are used to assign (bind) data values to a name for easier reference. There are three ways to declare variables: let, const, and var.

let and const are ES 6 values, and the only variable declaration operators you need right now. We will demonstrate the different between them by trying to do something similar with both:

const musicianName = "Woody Guthrie";
console.log(musicianName); // logs "Woody Guthrie"

musicianName = "Arlo Guthrie"; // VM111:4 Uncaught TypeError: Assignment to constant variable.

Trying to re-assign musicianName to a new value fails when you initially assigned the variable name using const… which stands for constant. If you want to be able to change a variable’s assignment value, use let.

let musicianName = “Woody Guthrie”; console.log(musicianName); // logs “Woody Guthrie”

musicianName = “Arlo Guthrie”; // no problems with this assignment! console.log(musicianName); // logs “Arlo Guthrie”

If you find variables confusing right now, I recommend that you begin by using let to declare all variables for now. Or you could use const and only change it to let if you get the same TypeError you see above.

var is the old way of declaring variable names. It behaves similarly to let. I recommend against using var and only include reference to it here so you won’t be confused when you see it in other people’s code. (Another good reason to use var is if your’e working with a codebase that has not yet migrated to ES 6).

One final point to remember: Variables are scoped - they can only be used inside the {curly brackets} within which they are declared.

Recap

You just learned a healthy smattering of JavaScript, the programming language of the browser. You will learn much more about JS and its ecosystem (including using it on the backend) throughout the rest of Part 4.

I strongly recommend reading/skimming Eloquent JavaScript as we go along the rest of Part 4. It is important to remember to not get bogged down. I probably only understood 25% of that book the first time I read it.

Exercises

There is a lot here. I am not asking for you to perfectly answer all of these questions, nor am I asking to you to memorize three chapters of Eloquent JavaScript before moving onto the next chapter. If you feel overwhelmed by these exercises, I recommend that you just quietly read through each question, reflect on it for 15 seconds, then move onto the next. If you don’t want to closely read Eloquent JavaScript, I recommend an approach called “Just put your eyes on each page.” So long as you let your eyes linger on the page for a minute (perhaps noticing italicized words), you can consider honor satisfied.

  1. What is the Internet?

  2. What is the World Wide Web?

  3. What are resources?

  4. Why do we have browsers?

  5. What are the 7 data types in JavaScript?

  6. What does the typeof operator do?

  7. Which data type is JavaScript’s workhorse?

  8. Functions are a special kind of JavaScript object. What makes them so special?

  9. How would you create a variable named “githubID” with a string value of “kevmo”?

  10. What are the two most important data structures in JavaScript?

  11. Read/skim Chapter 1, “Values, Types, and Operators” of Eloquent JavaScript. I strongly recommend typing most examples out in the JavaScript developer console yourself. Here are some companion questions:
    • What are values?
    • What is concatenation?
    • What are the two Boolean values?
    • Can an expression (a value like 3 < 2) evaluate to a Boolean?
    • Is 3 < 2 going to evaluate to a truthy or falsy value?
    • What are the two empty data types?
  12. Read/skim Chapter 2, “Program Structure” of Eloquent JavaScript. Here are some companion questions:
    • What are all of JavaScript’s keywords and reserved words? Write them down in your Coding Journal.
    • What are the three ways to create variables in JavaScript?
    • What is your strategy for using bindings going forward? (spoiler alert: There is no right answer).
    • Regarding functions: What is a side effect? What is a return value?
    • What is control flow? What is conditional execution?
  13. What is the difference between console.dir and console.log?

  14. How would you create an array containing the numbers 1, 2, 3, 4, 5, and 6? How would you console.log all of the members of that array?

  15. Why is it important to write comments in your code?

  16. Read Chapter 13, “JavaScript and the Browser”, of Eloquent JavaScript.