Everyone Can Learn Program
中文 Start learning
Core · FrontendLesson 5 of 8Free to read

JavaScript basics · Frontend: HTML, CSS and JavaScript

How do you give a page a brain?

Course contents

Why 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:

IdeaPythonJavaScript
printprint(x)console.log(x)
variablex = 1let x = 1; or const x = 1;
text with valuesf"Hi {name}" Hi ${name}
equal?=====
blockindentation{ }
functiondef f(a):function f(a) { } or const f = a => …
  • **const for 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, so 1 == "1" is true, which hides bugs.
  • "5" + 1 is "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 yourself

const 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);
Output
Ada scored 10
number string
Step by step
  1. L1name is a const: it will always be "Ada".
  2. L3score is a let, so we can give it a new value: 10.score = 10
  3. L4Inside backticks, ${...} drops a value into the text.Ada scored 10
  4. L5typeof tells you the type of a value.number string

== versus ===

Try it yourself

The loose == converts types before comparing, with surprising results.

console.log(1 == "1");
console.log(1 === "1");
console.log(0 == "");
console.log(0 === "");
Output
true
false
true
false
Step by step
  1. L1The string "1" is converted to the number 1, so they're "equal".true
  2. L2Different types: not equal. This is what you almost always want.false
  3. L3An empty string converts to 0. Surprise!true
  4. L4=== says no.false

Functions, if and for

Try it yourself

The 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));
  }
}
Output
1 odd 2
2 even 4
3 odd 6
Step by step
  1. L1A function with two parameters.
  2. L4An arrow function: takes n, returns n * 2.
  3. L6for (start; keep going while; after each round): i is 1, 2, 3.
  4. 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);
  1. A
    51
    4
  2. B
    6
    4
  3. C
    51
    51
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?

  1. Aconst userId = 42;
  2. Blet userId = 42;
  3. CuserId = 42;
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.

  1. PredictFollow the loop

    Type exactly what this prints.

  2. 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.

  3. 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

TermChineseDefinition
JavaScriptJavaScriptThe programming language every web browser runs.
console.logconsole.logPrints values to the console; JavaScript's print().
Template literal模板字符串Text in backticks where ${...} inserts values.