Getting startedChapter 4 of 21
Statements
The units a program is made of, and the order they run in.
One instruction at a time
A program is a list of statements. The engine runs them top to bottom, one after another, and each one does a single piece of work.
JavaScript
let total = 0;
total = total + 5;
total = total * 2;
console.log(total);Output
10
Order matters. Move the multiplication above the addition and the answer changes, because each statement works on whatever the ones before it left behind.
Semicolons
A semicolon ends a statement. JavaScript will insert missing ones for you, a rule called automatic semicolon insertion, and it mostly guesses right. Mostly is the problem:
JavaScript
function bad() {
return
{
ok: true
};
}
console.log(bad());Output
undefined
A semicolon was inserted straight after return, so the object below it is unreachable and the function returns nothing. Put the brace on the same line as return and it works.
Tip
This tutorial ends every statement with a semicolon. Whichever convention you pick, apply it everywhere: mixed styles are where these surprises hide.
Blocks
Curly braces group statements into a block, and anywhere one statement is allowed a block can go instead.
JavaScript
const hour = 9;
if (hour < 12) {
console.log('Morning');
console.log('Two statements, one block');
}Output
Morning Two statements, one block
Braces are optional for a single statement after if, and leaving them out has caused enough real bugs that most teams require them anyway.
Whitespace
JavaScript ignores extra spaces, tabs and blank lines between statements, so indentation is for humans rather than the engine. Two spaces per level is the common choice and the one used here.
Case matters
Names are case sensitive. total, Total and TOTAL are three different names, and mixing them up produces a quiet bug rather than an error.
JavaScript
const price = 10;
console.log(price);
console.log(typeof Price);Output
10 undefined
Test yourself
2 questionsWhy does returning an object on the line below return break?
Show the answer
A semicolon is inserted straight after return Automatic semicolon insertion ends the statement before it ever sees the object.
What decides the order statements run in?
Show the answer
Top to bottom, as written Which is why a statement can only use what the ones above it have already set up.
Syntax
The vocabulary: values, variables, operators, keywords and expressions.