The Grammar of JavaScript

Kindergarten, page 6 of 9. A two-minute read.

Every language has grammar rules. In English, sentences start with a capital letter and end with a full stop. JavaScript has its own rules too. Here are the big ones.

Statements

A statement is a single instruction. It's like one sentence in a recipe:

JavaScript
console.log("Step 1: Boil the water.");
console.log("Step 2: Add the rice.");
console.log("Step 3: Wait patiently. Do not eat raw rice.");

It prints

Step 1: Boil the water.
Step 2: Add the rice.
Step 3: Wait patiently. Do not eat raw rice.

JavaScript runs statements one at a time, from top to bottom. Change the order of the lines and you change the order of the output.

Semicolons

Each statement usually ends with a semicolon ;. It's JavaScript's full stop.

Now, here's a confession that Professor Semicolon really doesn't want you to hear: JavaScript will often let you leave semicolons out. It has a feature called Automatic Semicolon Insertion that tries to add them for you where it thinks they belong.

The problem is that its guesses are sometimes wrong, which can cause very confusing bugs.

So our rule in this book is simple: always end your statements with a semicolon. It keeps your code clear, it keeps you safe, and it keeps the Professor from crying in the staff room.

Case sensitivity

We mentioned this already, but it's so important it deserves to be said twice: JavaScript is case-sensitive. score, Score and SCORE are three completely different names to JavaScript.

Whitespace

JavaScript mostly ignores extra spaces, tabs, and blank lines. These two pieces of code do exactly the same thing:

JavaScript
console.log("Neat and tidy");
console.log(     "Messy, but it still works"      )   ;

It prints

Neat and tidy
Messy, but it still works

But please, for the love of all things good, write neat code. You'll be reading your own code a lot more often than you write it, and future-you will thank present-you for keeping things tidy. We use two spaces to indent code inside curly braces in this book, which is a very common style.

Curly braces

You'll soon see code that looks like this:

JavaScript
if (hungry) {
  console.log("Eat something!");
}

Those curly braces { } group statements together into a block. Professor Curly (our mascot) is very proud of them. Whenever you open a curly brace {, you must close it with } later. Same with parentheses ( ) and square brackets [ ]. They always come in pairs, like socks. (Unlike socks, they don't vanish in the laundry.)

Tip

Most code editors automatically add the closing bracket when you type an opening one. If yours doesn't, get in the habit of typing both and then filling in the middle.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning