Now that you have the basics of HTML and CSS under your belt, we're going to start learning our first programming language: JavaScript. Remember, web browsers can only do three things: display content with HTML, style it with CSS, and change what's displayed with JavaScript. Because all browsers support JavaScript, it's the de facto programming language of the web.

We're going to take a detour away from the aesthetically pleasing and obviously useful world of web pages, so that we can learn some programming fundamentals. But don't worry! We'll be back in no time.

Like earlier, I'm going to assume you're using Google Chrome for these lessons. Chrome includes a nice little console that lets you type in JavaScript code. To access it, click on the ☰ button, go to the More Tools menu, and click Developer Tools. Go to the Console tab on the window that pops up at the bottom of the screen. As a shortcut, you can also press Cmd + Option + J on a Mac or Ctrl + Shift + J on a PC.

Here at the > prompt, you can type JavaScript and see what it does. Try typing 1 + 2; and pressing Enter.

Congratulations! You just ran your first JavaScript code.

You should see something like:

> 1 + 2;
3

JavaScript took your code - 1 + 2 - evaluated it, and returned the result - 3.

The semicolon at the end of the line tells JavaScript to run everything before it. You'd think JavaScript would know on its own, wouldn't you?

Now try these:

  • 4 - 3;

  • 5 * 6;

  • 10 / 2;

  • 9 / 2;

  • 7 + 8 * 9;

  • (7 + 8) * 9;

Try some other arithmetic yourself. Play around with the % operator, called modulo. It will give you the remainder of dividing two numbers. Don't be fooled into thinking it has something to do with percentages!

+, -, *, /, and % are called operators. An operator is a special character (or characters) that indicates an action to be performed.

Try dividing 0 by 0. The result, NaN, stands for not a number. In JavaScript, NaN is actually considered a type of number (bizarre as that may seem).

Try dividing any other number by 0. The result, Infinity, is also a number in JavaScript.

Terminology


  • +, -, *, /, and % are called operators. An operator is a special character (or characters) that indicates an action to be performed.

  • 9 % 2; returns the remainder of 9 divided by 2. % is called modulo.

  • 0 / 0; returns NaN, which stands for not a number. NaN is a type of number.

  • Infinity is also a number.

Examples


Basic arithmetic works just like you'd expect:

1 + 2;
4 - 3;
5 * 6;
9 / 2;
7 + 8 * 9;
(7 + 8) * 9;

Keyboard Shortcuts


  • For Macs: Cmd + Option + J opens the JavaScript console in Chrome.
  • For Windows: Ctrl + Shift + J opens the JavaScript console in Chrome.