Topic 0.4
Your First Program
In one line
A JavaScript program is a list of statements run from top to bottom; semicolons end statements (and are added automatically in most, but not all, places), comments are notes the engine ignores, and every name is case-sensitive.
Think of it like this
Steps on a recipe card. Each numbered step is one statement: "boil the water", "add the rice". You do them in order, top to bottom. The full stop at the end of each step is the semicolon. Notes in the margin like "Grandma's tip: use less salt" are comments: helpful to the reader, ignored by the cook.
Words you'll meet
New words in this topic, in plain English. Come back here whenever one feels fuzzy.
- Program
- A set of instructions the computer follows, in order.
- Statement
- One complete instruction, like declaring a value or printing it.
- Expression
- Code that produces a value, like
2 + 3or"Hi". - Semicolon
- The
;that marks the end of a statement. - ASI
- Automatic Semicolon Insertion: the engine's rule for adding missing semicolons at some line breaks.
- Comment
- A note in the code (
//or/* */) that the engine ignores. - Case-sensitive
- Capital and small letters count as different:
nameandNameare two names. - Identifier
- A name you give to something, like
priceoruserName. - Reserved word
- A word the language already uses, like
iforreturn, so you can't use it as a name.
Step by step
01Plan it in plain words
Our first program works out a shopping bill: 3 notebooks at 40 rupees and 2 pens at 15. Before writing code, write the steps as comments. This is how professionals start too.
// 1. Remember the prices and how many of each
// 2. Work out the total
// 3. Show the total02Turn each step into statements
const creates a named value (you'll learn it fully in Phase 1). Each line is one statement ending with ;. The engine runs them in this exact order, so total can use the values declared above it.
// 1. Prices and quantities
const notebookPrice = 40;
const notebooks = 3;
const penPrice = 15;
const pens = 2;
// 2. The total
const total = notebookPrice * notebooks + penPrice * pens;
// 3. Show it
console.log("Total:", total);03See how the engine reads it
Top to bottom, one statement at a time. Comments and blank lines are skipped. If a statement throws an error, the ones after it never run.
04Know where semicolons matter
These two lines look like two statements, but because the second starts with [, the engine reads them as one: 1[1, 2].forEach(...). That reads a property of the number 1 that doesn't exist (undefined), then calls forEach on it.
const a = 1
[1, 2].forEach((n) => console.log(n))
// TypeError: Cannot read properties of undefined (reading 'forEach')05Check the capitals
Every built-in name must be spelled with exactly the right capitals. When an error says ... is not defined or ... is not a function, check the capitals first.
console.log("works");
Console.log("fails"); // ReferenceError: Console is not definedTry it yourself
- 1
Add an item
In the bill example, add an eraser at 5 rupees, 4 of them. Predict the new total before you run it (it should be 170).
- 2
Switch a line off
Put
//in front of theconsole.log("Pens:", ...)line. Predict the console output, then run it. - 3
Repair the glued lines
In the third example, add one semicolon so the program prints
item 1,item 2andnever printed. Try both places: the end of line 2 and the start of line 3. - 4
Fix the bad return
In the ASI example, move the
{up onto the same line asreturningetUserBad. What does it print now? (Also remove the;after"Asha"inside the object, since object properties are separated by commas.)
Code & diagrams
Comments are ignored when the code runs. Try adding a third item.
Preview
Console
Nothing logged yet.Expected console output
Notebooks: 120
Pens: 30
Total: 150In the bad one, a semicolon is inserted right after `return`, so it returns nothing. The braces below are then read as a separate block of code, never reached.
Preview
Console
Nothing logged yet.Expected console output
good: { name: 'Asha' }
bad: undefinedAdd a `;` after `const a = 1` (or at the start of the next line) and both items print.
Preview
Console
Nothing logged yet.Expected console output
Before the problem
Uncaught TypeError: Cannot read properties of undefined (reading 'forEach')`console.Log` doesn't exist, so it's `undefined`. Using a name that was never declared (`scoRe`) is a ReferenceError.
Preview
Console
Nothing logged yet.Expected console output
10 20 30
function undefined
Uncaught ReferenceError: scoRe is not definedBreak it on purpose
Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.
Break #1
Wrong capital in a built-in method
Write document.getElementByID("bill") (capital D at the end).
Break #2
A comment that never ends
Start a comment with /* and forget the closing */.
Break #3
Use a reserved word as a name
Write const class = "5B";.
Myth vs fact
Myth
Semicolons are optional, so they never matter.
Fact
ASI fills most of them in, but not after return with a line break, and not before lines that start with (, [ or a backtick. Either always write them or know these rules (many teams let a formatter add them).
Myth
More comments always make code better.
Fact
Comments that repeat the code (// add 1 above count + 1) just add noise and go out of date. Good comments explain why something is done, or warn about a trap.
Myth
Console.log and console.log are the same thing.
Fact
JavaScript is case-sensitive. Only console.log exists.
Pro corner
Extra depth for experienced readers. New to this? Skip it for now and come back later.
- ▸
ASI is defined precisely in the ECMAScript spec: a semicolon is inserted when the next token can't be parsed, at the end of the input, or after a line break in a restricted production:
return,break,continue,throw,yield, postfix++/--, and before=>in arrow functions. Learning these few cases is all ASI really requires. - ▸
Lines starting with
(,[, a backtick,+,-or/are the hazards in no-semicolon style. Linters like ESLint (ruleno-unexpected-multiline) catch these. Prettier'ssemi: falseoption adds a leading;where needed. - ▸
Scripts can opt into strict mode with
"use strict";as the first statement; modules and class bodies are strict automatically. Strict mode turns silent mistakes into errors, for example assigning to an undeclared name throws a ReferenceError instead of creating a global. - ▸
Since ES2023, a file may start with a hashbang line like
#!/usr/bin/env node, so a script can run directly from a Unix shell. Identifiers can use Unicode letters (const café = 1is valid), though ASCII names are easier for teams to type.
Remember this
- 1
A statement is one complete instruction, like
const price = 40;(remember a value) orconsole.log(price);(print it). The engine runs statements one after another, from top to bottom, unless something like anifor a loop changes the order (Phase 2). An expression is a piece of code that produces a value, like40 * 3or"Hi " + name; statements are often built from expressions. - 2
A semicolon
;marks the end of a statement. JavaScript has a rule called ASI (Automatic Semicolon Insertion): if a line break comes where the code can't continue, the engine acts as if you had typed a semicolon. That's why code without semicolons usually works. Both styles are common; the important thing is to know where ASI fails. - 3
ASI fails in two ways. First, after
return,break,continueandthrow, a line break always ends the statement, soreturnalone on a line returnsundefinedand the value on the next line is ignored. Second, if the next line starts with(,[or a backtick, the engine does not insert a semicolon: it glues the two lines together, as inconst a = 1followed by[1, 2].forEach(...), which becomes1[1, 2].forEach(...). If you leave semicolons out, start such lines with;. - 4
Comments are notes for people.
// like thisruns to the end of the line./* like this */can span many lines but can't be nested./** ... */is a JSDoc comment that editors read to show hints about a function. Use comments to explain why the code does something; the code itself already says what. A quick trick while learning: put//in front of a line to switch it off without deleting it. - 5
JavaScript is case-sensitive:
score,ScoreandSCOREare three different names, andconsole.logworks whileConsole.logdoesn't exist. Built-in names have fixed capitals:document.getElementById(capitalI, smalld),Math.max,JSON.parse. A wrong capital is one of the most common beginner bugs, and it shows up as a ReferenceError or... is not a function. - 6
Names you create (identifiers) may contain letters, digits,
_and$, but can't start with a digit and can't be reserved words likeif,let,classorreturn. The usual style is camelCase:totalPrice,userName. Whitespace (spaces, tabs, line breaks) mostly doesn't matter to the engine, so indent to make the structure clear for people. A tool called Prettier (the Format button in Hectal's editor uses it) does this for you.
Explain it without notes
What is the difference between a statement and an expression?
Explain Automatic Semicolon Insertion and give two cases where it surprises people.
What does case-sensitive mean in JavaScript, and what errors does a wrong capital cause?
When should you write a comment, and when shouldn't you?
Practice
Write a program that stores the length (8) and width (5) of a room, works out the area, and logs Area: 40, with a comment for each step.
This code prints undefined. Fix it so it prints { ok: true }:
``js
function check() {
return
{ ok: true }
}
console.log(check())
Find and fix the two bugs: const UserName = "Ravi";
console.Log("Hi", userName);
Trade-offs
- ↔
Always writing semicolons means never thinking about ASI hazards, at the cost of a little typing; leaving them out looks cleaner but you must know the few dangerous line starts (or let a formatter handle it). Pick one style per project and let a tool enforce it.
Done when you can
I can write a short program as a list of statements that runs top to bottom.
I can explain what ASI does and spot the
returnand leading-bracket traps.I can write line and block comments, and switch a line off with
//.I know names are case-sensitive and check capitals when I see
not defined.I know the rules for naming things and avoid reserved words.