JavaScript Tutorial
JavaScript Statements
A program is a list of statements. End each one with a semicolon so the next line is not a surprise.
A program is a list
A statement is one instruction: declare a name, assign a value, call a function, or change the page. The browser runs them from top to bottom unless a later chapter changes the flow.
Put one statement on each line. End it with a semicolon. That is the house style on StudyGrid.
Example
let count = 0;
count = count + 1;
console.log(count);Run this in /javascript/try. Open it with Try it in JavaScript. That editor.
Order matters
A name must exist before you use it. A line that logs score before score is declared will throw. Swap the lines and the same program works.
Example
let score = 10;
console.log(score);
score = 20;
console.log(score);First the name is created. Then it is printed. Then it is changed. Then it is printed again. That sequence is the program.
Semicolons
A semicolon ends a statement. JavaScript can insert one for you at a line break. It does not always guess what you meant. Write the semicolon yourself so the next line is not glued to this one.
Example
let a = 1;
let b = 2;
console.log(a + b);You can put more than one statement on a line if each has a semicolon. Do not. One statement per line is easier to scan and easier to debug.
A missing semicolon can make the next line part of this one. The error message often points at thenext line. Check the line above it.
White space
Spaces, tabs, and blank lines do not change meaning between tokens. Use them so a human can read the file. Indent the body of a block. Leave a blank line between groups of related statements.
let n=3; and let n = 3; do the same work. Prefer spaces around=. White space is for people. The engine ignores the extra spaces.
Blocks
Braces group statements into a block. A block is the body of an if, a loop, or a function. The statements inside still run in order. They still end with semicolons.
Example
let score = 12;
if (score >= 10) {
console.log("pass");
console.log(score);
}The if line does not take a semicolon after the closing brace. The statements inside the braces do.
Expressions vs statements
An expression produces a value: 2 + 2, "hi", score. A statement does something with that value: assign it, log it, or return it. You will mix them on every line.
| Kind | Example |
|---|---|
| Expression | 1 + 2 |
| Statement | let total = 1 + 2; |
| Statement | console.log(total); |
Read top to bottom
Until you meet functions and events, assume every line runs once, in order, as soon as the script loads. That is enough to follow the next chapters.
Next: syntax — identifiers, literals, case, and reserved words.