15 minutes, beginner
JavaScript: your first program
By the end you’ll know what variables, choices and loops are, and you’ll have changed a real program to make it behave differently.
1. Say it
A program is a list of instructions the computer follows in order. These are the building blocks you’ll meet today.
| JavaScript | What it does | Example |
|---|---|---|
let | Makes a variable, a labelled box that holds a value | let age = 15; |
"text" | A piece of text, called a string, always in quotes | "Sam" |
15 | A number, with no quotes | let age = 15; |
console.log() | Prints a message | console.log("Hi"); |
if and else | Makes a choice between two paths | if (age >= 18) { ... } |
for | Repeats something, called a loop | for (let i = 1; i <= 3; i++) |
+ | Joins text, or adds numbers | "Hi " + name |
Tip: Lines usually end with a semicolon, like full stops in a sentence. Text goes in quotes. Numbers don’t.
2. Know it
Together, the three web languages split the work. HTML says what is on a page, CSS says how it looks, and JavaScript says what it does. It runs inside your browser, which is how pages respond when you click, type or scroll.
Numbers and text behave differently, which surprises almost every beginner. In JavaScript, 5 + 1 gives 6, but "5" + 1 gives "51", because the quotes make the 5 into text, and plus then joins text instead of adding.
When a program runs, it goes line by line from the top. The first three lines below store values. Everything after them uses those values, so changing one value changes the whole result.
3. Use it
Change the three highlighted values, then press Run to see what the program prints. Then try the challenges.
// Change the three values, then press Run.
let name = "";
let age = ;
let times = ;
console.log("Hello, " + name + "!");
console.log("Next year you will be " + (age + 1) + ".");
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are under 18.");
}
for (let i = 1; i <= times; i++) {
console.log("Counting: " + i);
}
What the program prints:
Press Run to see what the program prints.
- Challenge 1: change the name to your own.To do
- Challenge 2: make the program print “You are an adult.” (Which value decides that?)To do
- Challenge 3: make it count up to 5.To do
Notice: You changed three values and the whole program responded. The name changed the greeting, the age changed the choice and the number of times changed the loop. That’s what variables are for.
This page runs a ready-made program, and the three values are yours to change. That keeps it safe, and nothing you type is saved or sent anywhere. To run your own JavaScript later, a browser’s built-in developer tools work well.
4. Check it
Done!
You’ve met variables, choices and loops, and changed a program to make it behave differently.