JavaScript basics · Frontend: HTML, CSS and JavaScript
How do you give a page a brain?
Course contentsWhy you need it
HTML is the content and CSS is the look; JavaScript is the behaviour. Every button that does something, every form that checks your input, every page that updates without reloading runs JavaScript. It's also the only language every browser runs, which makes it the most widely used language in the world.
The intuition
If you know some Python, most ideas carry over; the punctuation changes:
| Idea | Python | JavaScript |
|---|---|---|
print(x) | console.log(x) | |
| variable | x = 1 | let x = 1; or const x = 1; |
| text with values | f"Hi {name}" | Hi ${name} |
| equal? | == | === |
| block | indentation | { } |
| function | def f(a): | function f(a) { } or const f = a => … |
- **
constfor values you won't reassign,let** for ones you will. Using a name you never declared is an error. - Always compare with **
===**. The double==converts types first, so1 == "1"is true, which hides bugs. "5" + 1is"51": with a string,+joins text.
Press Run: whatever console.log prints appears in the Output tab.
Definition
let / const
Declare a variable. const can't be reassigned; let can.
Strict equality (===)
True only when both the type and the value are the same. 1 === "1" is false.
Arrow function
A short way to write a function: const double = n => n * 2. With braces you need return: n => { return n * 2; }.
Examples
Variables and template strings
Try it yourselfconst never changes, let can, and backticks build text from values.
const name = "Ada";
let score = 7;
score = score + 3;
console.log(`${name} scored ${score}`);
console.log(typeof score, typeof name);Ada scored 10 number string
- L1name is a const: it will always be "Ada".
- L3score is a let, so we can give it a new value: 10.
score = 10 - L4Inside backticks, ${...} drops a value into the text.
Ada scored 10 - L5typeof tells you the type of a value.
number string
== versus ===
Try it yourselfThe loose == converts types before comparing, with surprising results.
console.log(1 == "1");
console.log(1 === "1");
console.log(0 == "");
console.log(0 === "");true false true false
- L1The string "1" is converted to the number 1, so they're "equal".
true - L2Different types: not equal. This is what you almost always want.
false - L3An empty string converts to 0. Surprise!
true - L4=== says no.
false
Functions, if and for
Try it yourselfThe same building blocks as Python, with braces.
function area(w, h) {
return w * h;
}
const double = n => n * 2;
for (let i = 1; i <= 3; i++) {
if (i % 2 === 0) {
console.log(i, "even", area(i, i));
} else {
console.log(i, "odd", double(i));
}
}1 odd 2 2 even 4 3 odd 6
- L1A function with two parameters.
- L4An arrow function: takes n, returns n * 2.
- L6for (start; keep going while; after each round): i is 1, 2, 3.
- L7% is the remainder; even numbers leave 0.
Common mistakes
Using ==
== converts types, so "" == 0 and "1" == 1 are both true. Use === and !== everywhere.
+ with text
Values from a text box are strings: "5" + 1 is "51". Convert first with Number(text).
Forgetting let or const
total = 0 without a declaration is an error here (and a hidden global in old code). Declare every variable.
Quick quiz
1. What does this print?
console.log("5" + 1);
console.log("5" - 1);Show the answer
Answer: A
+ with a string joins text. - only works on numbers, so "5" is converted to 5.
2. You store a user's id and it will never be reassigned. How do you declare it?
Show the answer
Answer: A
const says "this name always points to this value", and the code tells readers so.
Practice
3 exercises in three steps: predict what a program prints, change a program to meet a new requirement, then write one from scratch. Your code runs in the browser and is checked the moment you submit.
- PredictFollow the loop
Type exactly what this prints.
- ModifyA PIN check that lets in too much
The PIN comes from a text box, so it's a string. This check accepts
"01234"and" 1234"too. Make it accept exactly"1234"and nothing else. - WriteFormat a price
Shops store prices in cents to avoid rounding errors. Write
formatPrice(cents)that returns the price as text with a dollar sign and two decimals:formatPrice(1250)→"$12.50"formatPrice(5)→"$0.05"
Practise this lesson
Open the interactive lesson to edit and run these examples and solve the exercises with instant feedback. Free to start, no sign-up.
Interactive lessons open in order. If you have not done the earlier ones yet, you start at the course map.
Terms in this lesson
| Term | Chinese | Definition |
|---|---|---|
| JavaScript | JavaScript | The programming language every web browser runs. |
| console.log | console.log | Prints values to the console; JavaScript's print(). |
| Template literal | 模板字符串 | Text in backticks where ${...} inserts values. |