Skip to content
Subjects
  • 1 Getting started
    1.1

    Your first program

    A program 程序 is a list of instructions for the computer. In JavaScript, each instruction is a statement 语句, and the computer runs the statements from top to bottom.

    console.log(...) prints a value in the console 控制台, the text area under the code:

    console.log("Hello, world!");
    console.log(7 * 6);   // 42
    
    • Text goes inside quotes: "Hello" or 'Hello'. Numbers do not.
    • End each statement with a semicolon ;. JavaScript can often guess where one is missing, but writing it is clearer.
    • JavaScript is case-sensitive 区分大小写: console.log works, Console.Log does not.

    To put a quote mark inside text, use the other kind of quote around it. A backslash 反斜杠 starts a special character: \n starts a new line.

    console.log('She said "hi"');        // She said "hi"
    console.log("It's mine");            // It's mine
    console.log("Line one\nLine two");   // two lines: Line one, then Line two
    

    console.log can print several values at once. It puts one space between them:

    console.log("Total:", 3 + 4);   // Total: 7
    console.log(1, 2, 3);           // 1 2 3
    
    Vocabulary
    English
    program/ˈprəʊɡræm/
    statement/ˈsteɪtmənt/
    console
    case-sensitive/keɪs ˈsensɪtɪv/
    backslash
    1.2

    Comments & code style

    A comment 注释 is a note for people. JavaScript ignores it when the program runs.

    // A one-line comment starts with two slashes.
    console.log("This line runs");   // a comment can follow code
    
    /* A block comment
       can cover several lines. */
    console.log("So does this one");
    

    Good style 风格 makes code easy to read:

    • Indent 缩进 the lines inside { } by two or four spaces, and do it the same way every time.
    • Give variables names that say what they hold: total, not t.
    • JavaScript names use camelCase 驼峰命名法: firstName, scoreTotal.
    // Work out the area of a rectangle
    const width = 4;
    const height = 3;
    console.log(width * height);   // 12
    

    Common mistakes

    • Text needs matching quotes: "Hi' is an error.
    • console.log is all lower case: Console.log and console.Log are errors.
    • Everything after // on a line is ignored, so // console.log(x) prints nothing.
    • "It's" is fine, but 'It's' ends the text at the apostrophe: an error.
    Vocabulary
    English
    comment/ˈkɒment/
    style/staɪl/
    indent/ˌɪnˈdent/
    camelCase/ˈkæml keɪs/
  • 2 Values, variables & types
    2.1

    let and const

    A variable 变量 is a named box that holds a value. Make one with let or const, then use its name:

    let score = 10;
    score = score + 5;      // let: the value can change
    console.log(score);     // 15
    
    const name = "Mei";     // const: the name cannot be reassigned
    console.log(name);      // Mei
    
    • = means assign 赋值: work out the right side, then store it in the box on the left.
    • Use const by default. Use let only when the value must change later.
    • Reassigning a const is an error: name = "Tom" is not allowed. A const object or array can still have its contents changed.

    Changing a variable by a step is so common that it has short forms 简写:

    Short form Same as
    count += 5 count = count + 5
    count -= 3 count = count - 3
    count *= 2 count = count * 2
    count++ count = count + 1
    let count = 10;
    count += 5;             // 15
    count -= 3;             // 12
    count *= 2;             // 24
    count++;                // 25
    console.log(count);     // 25
    
    Vocabulary
    English
    variable/ˈveərɪəbl/
    assign
    short form
    2.2

    Numbers & maths

    These examples use the number type for whole and decimal values. BigInt is a separate integer type. The arithmetic operators 运算符 are:

    Operator Meaning Example Result
    + - add, subtract 7 - 2 5
    * / multiply, divide 7 / 2 3.5
    % remainder 余数 7 % 2 1
    ** power 2 ** 3 8
    console.log(7 / 2);              // 3.5
    console.log(Math.floor(7 / 2));  // 3   (whole-number division)
    console.log(7 % 2);              // 1   (odd numbers leave 1)
    console.log(2 + 3 * 4);          // 14  (* before +)
    console.log((2 + 3) * 4);        // 20
    
    Seven dots grouped into three pairs with one dot left over, beside Math.floor of 7 over 2 equals 3, 7 percent 2 equals 1 and 7 over 2 equals 3.5
    Seven shared into pairs: three whole pairs, one left over.

    Math holds useful functions:

    console.log(Math.round(2.5));    // 3
    console.log(Math.max(4, 9, 2));  // 9
    console.log(Math.sqrt(49));      // 7
    

    Math.floor and % work as a pair: one gives the whole groups, the other what is left. Here they turn minutes into hours and minutes:

    const minutes = 135;
    const hours = Math.floor(minutes / 60);   // 2 whole hours
    const rest = minutes % 60;                // 15 minutes left over
    console.log(hours + " h " + rest + " min");   // 2 h 15 min
    
    • Math.random() gives a random 随机 number from 0 up to (not including) 1. Math.floor(Math.random() * 6) + 1 is a dice roll from 1 to 6.
    • Decimals are stored in binary, so 0.1 + 0.2 prints 0.30000000000000004. Round a result before you show it: (0.1 + 0.2).toFixed(2) is "0.30".
    Vocabulary
    English
    operator/ˈɒpəreɪtə/
    remainder/rɪˈmeɪndə/
    random/ˈrændəm/
    2.3

    Types & conversion

    Every value has a type 类型. typeof tells you which:

    console.log(typeof 42);         // number
    console.log(typeof "42");       // string
    console.log(typeof true);       // boolean
    console.log(typeof undefined);  // undefined
    
    • A variable made with let x; and no value is undefined.
    • null means "no value", set on purpose.

    + with a string joins instead of adding, so convert 转换 text to a number first:

    console.log("5" + 1);           // 51  (joined)
    console.log(Number("5") + 1);   // 6   (added)
    console.log(parseInt("12px"));  // 12  (reads the number at the start)
    console.log(String(9) + "!");   // 9!
    
    • A text that is not a number gives NaN ("not a number"): Number("abc") is NaN.
    • -, * and / convert text to a number by themselves ("6" * 2 is 12), but do not rely on it: convert on purpose.

    Common mistakes

    • = assigns; it does not compare. Comparing uses === (topic 4).
    • "5" + 1 is "51". Convert input with Number(...) before doing maths with it.
    • Math.round(2.5) is 3, but Math.round(-2.5) is -2: it rounds halves up, towards the larger number.
    Vocabulary
    English
    type/taɪp/
    convert
  • 3 Strings
    3.1

    Characters & length

    A string 字符串 is text inside quotes. With simple letters, each character 字符 has one position, its index 索引; the first index is 0. JavaScript counts UTF-16 code units: an emoji may take two positions.

    const word = "Script";
    console.log(word.length);     // 6
    console.log(word[0]);         // S
    console.log(word[2]);         // r
    console.log(word.at(-1));     // t  (counts back from the end)
    console.log(word[word.length - 1]);   // t
    
    • The last index is length - 1. word[6] is undefined, not an error.
    • Strings are immutable 不可变: word[0] = "s" cannot change the string and throws a TypeError in strict mode. Build a new string instead.

    A for...of loop visits the characters one by one. This counts the letter a:

    const fruit = "banana";
    let count = 0;
    for (const ch of fruit) {
      if (ch === "a") {
        count += 1;
      }
    }
    console.log(count);   // 3
    

    Join strings with +, which is called concatenation 拼接:

    const first = "Ada";
    const last = "Lovelace";
    console.log(first + " " + last);   // Ada Lovelace
    
    Vocabulary
    English
    string/strɪŋ/
    character/ˈkærɪktə/
    index/ˈɪndeks/
    immutable/ɪˈmjuːtəbl/
    concatenation/kənˌkætəˈneɪʃn/
    3.2

    String methods

    A method 方法 is a function that belongs to a value. Call it with a dot. A string method gives back a new value and leaves the original alone.

    const city = "  Hong Kong ";
    console.log(city.trim());                 // Hong Kong
    console.log(city.trim().toUpperCase());   // HONG KONG
    console.log(city.length);                 // 12  (the spaces are still there)
    
    Method Meaning Example Result
    .toUpperCase() / .toLowerCase() change case "Hi".toLowerCase() "hi"
    .trim() remove spaces at both ends " hi ".trim() "hi"
    .includes(t) does it contain t? "cat".includes("a") true
    .indexOf(t) first position of t, or -1 "cat".indexOf("t") 2
    .slice(a, b) characters from a up to (not including) b "Script".slice(0, 3) "Scr"
    .split(sep) break into an array "a,b,c".split(",") ["a","b","c"]
    .replace(a, b) swap the first a for b "cat".replace("c", "b") "bat"
    const email = "[email protected]";
    const at = email.indexOf("@");
    console.log(email.slice(0, at));          // mei
    console.log(email.slice(at + 1));         // school.org
    console.log(email.split("@"));            // ["mei","school.org"]
    

    Methods can be combined. This tidies a name typed in any case: the first letter in capitals, the rest in small letters:

    const typed = "mEI";
    const nice = typed[0].toUpperCase() + typed.slice(1).toLowerCase();
    console.log(nice);                            // Mei
    console.log("a-b-c".replaceAll("-", "/"));    // a/b/c  (every match, not just the first)
    
    The string mei@school.org in numbered boxes from 0 to 13, with the @ at index 3; slice 0 to at covers mei and slice at plus 1 covers school.org
    indexOf finds the @ at 3; the two slices take the parts either side of it.
    Vocabulary
    English
    method/ˈmeθəd/
    3.3

    Template literals

    A template literal 模板字面量 is a string written between backticks (on most keyboards, the key left of 1). Put any expression 表达式 inside ${ } and its value is placed into the text:

    const name = "Mei";
    const age = 17;
    console.log(`${name} is ${age} years old.`);   // Mei is 17 years old.
    console.log(`Next year: ${age + 1}`);          // Next year: 18
    
    • Backticks can also hold several lines of text.
    • This is easier to read than many + signs: compare "Hi " + name + "!" with `Hi ${name}!`.
    const price = 4.5;
    console.log(`Two cost $${(price * 2).toFixed(2)}`);   // Two cost $9.00
    

    Common mistakes

    • ${ } only works inside backticks. In "Hi ${name}" the text is printed exactly as typed.
    • Methods do not change the string: city.trim() on its own line does nothing. Store the result: const clean = city.trim();.
    • slice(a, b) stops before b, just like the last index is length - 1.
    Vocabulary
    English
    template literal
    expression/ekˈspreʃn/
  • 4 Decisions
    4.1

    Booleans & comparisons

    A Boolean 布尔值 is either true or false. A comparison 比较 gives a Boolean:

    Operator Meaning Example Result
    === equal (same value and same type) 5 === 5 true
    !== not equal 5 !== 3 true
    < > less than, greater than 2 > 7 false
    <= >= at most, at least 7 >= 7 true
    console.log(5 === 5);     // true
    console.log(5 === "5");   // false  (a number is not a string)
    console.log(5 == "5");    // true   (== converts first: avoid it)
    
    • Always use === and !==. The older == converts types first and gives surprising answers.

    For Boolean conditions, use the logical operators 逻辑运算符 below. With other values, && and || return one of their operands; they do not always return a Boolean:

    • && (and): true only if both sides are true.
    • || (or): true if at least one side is true.
    • ! (not): turns true into false and back.
    const age = 15;
    console.log(age >= 13 && age <= 19);   // true   (a teenager)
    console.log(age < 5 || age > 65);      // false
    console.log(!(age > 18));              // true
    
    Truth table for a and b: a && b is true only in the row where both are true; a || b is false only where both are false
    And needs both sides true; or needs at least one.
    Vocabulary
    English
    Boolean/ˈbuːlɪən/
    comparison/kəmˈpærɪsn/
    logical operator/ˈlɒdʒɪkl ˈɒpəreɪtə/
    4.2

    if / else if / else

    An if statement runs a block 代码块 of code when its condition 条件 is truthy 真值 (treated as true). With Boolean conditions, this means the value true. else if tests another condition; else catches everything left:

    const mark = 72;
    if (mark >= 80) {
      console.log("A");
    } else if (mark >= 60) {
      console.log("B");
    } else {
      console.log("C");
    }
    // prints B
    
    • JavaScript checks the conditions from the top and runs only the first true branch 分支.

    Any value can be a condition. Six values are falsy 假值, treated as false; every other value is truthy:

    Falsy values Truthy examples
    false, 0, "" (empty text), null, undefined, NaN true, 5, "0", "no", [] (an empty array)

    So if (!typed) is a short way to ask "is the text empty?":

    const typed = "";
    if (!typed) {
      console.log("Please type your name.");
    }
    // prints Please type your name.
    
    • The condition goes in round brackets; the code to run goes in curly braces { }.

    Brackets group the parts of a longer test. A year is a leap year if it divides by 4 but not by 100, or if it divides by 400:

    function isLeap(y) {
      return (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
    }
    console.log(isLeap(2024), isLeap(1900), isLeap(2000));   // true false true
    

    The order of else if tests matters. Put the strictest test first:

    const temp = 35;
    if (temp > 30) {
      console.log("hot");
    } else if (temp > 20) {
      console.log("warm");   // skipped: the first branch already ran
    }
    // prints hot
    
    Vocabulary
    English
    block/blɒk/
    condition/kənˈdɪʃn/
    branch/bræntʃ/
    falsy
    truthy
    4.3

    switch

    A switch compares one value against several fixed cases. It is neater than a long else if chain when every test is "is it equal to …?":

    const day = "Sat";
    switch (day) {
      case "Sat":
      case "Sun":
        console.log("weekend");
        break;
      case "Fri":
        console.log("nearly there");
        break;
      default:
        console.log("school day");
    }
    // prints weekend
    
    • switch compares with ===, so case 1: does not match the string "1".
    • break ends the switch. Without it, the code falls through into the next case.
    • default runs when no case matches, like a final else.
    • Two cases with no code between them share the same code, as "Sat" and "Sun" do here.

    Common mistakes

    • if (x = 5) assigns instead of comparing, and the test is then always true. Write if (x === 5).
    • if (age > 13 && < 19) is an error: repeat the variable, age > 13 && age < 19.
    • A missing break in a switch runs the next case too.
    • The text "0" and an empty array [] are truthy. Test arr.length === 0 for an empty array.
  • 5 Loops
    5.1

    for loops

    The three parts of a for loop, and the order they run in

    A loop 循环 repeats a block of code. A for loop is best when you know how many times. Its brackets hold three parts, separated by semicolons:

    for (let i = 1; i <= 3; i++) {
      console.log(i);
    }
    // 1
    // 2
    // 3
    
    1. start: let i = 1 runs once, before the loop.
    2. condition: i <= 3 is checked before every pass; the loop stops when it is false.
    3. step: i++ (add 1 to i) runs after every pass.

    Each pass through the loop is one iteration 迭代. Change the step to count in other ways:

    let line = "";
    for (let i = 10; i > 0; i -= 3) {
      line += i + " ";
    }
    console.log(line);   // 10 7 4 1
    

    The accumulator 累加器 pattern makes a variable before the loop and updates it in every pass:

    let total = 0;
    for (let n = 1; n <= 5; n++) {
      total += n;          // the same as total = total + n
    }
    console.log(total);    // 15
    

    A loop inside a loop: the inner loop runs all its passes for each pass of the outer loop. Here 3 rows × 4 columns = 12 inner passes:

    for (let row = 1; row <= 3; row++) {
      let line = "";
      for (let col = 1; col <= 4; col++) {
        line += String(row * col).padStart(4);
      }
      console.log(line);
    }
    //    1   2   3   4
    //    2   4   6   8
    //    3   6   9  12
    

    let line = ""; sits inside the outer loop, so each row starts empty.

    Vocabulary
    English
    loop/luːp/
    iteration/ˌɪtəˈreɪʃn/
    accumulator/əˈkjuːmjʊleɪtə/
    5.2

    while loops

    A while loop repeats while its condition is true. Use it when you do not know in advance how many passes you need:

    let money = 100;
    let years = 0;
    while (money < 200) {
      money = money * 1.1;   // 10% interest each year
      years++;
    }
    console.log(years);      // 8
    

    A trace table 跟踪表 follows the variables pass by pass. The first three years:

    Pass money < 200? money after years after
    1 100 < 200, yes 110 1
    2 110 < 200, yes 121 2
    3 121 < 200, yes 133.1 3

    After pass 8 money is about 214.4, so the test money < 200 is false and the loop stops with years at 8.

    • The condition is checked before each pass, so the body may run zero times.
    • If the condition stays true and no break or other exit is reached, you get an infinite loop 无限循环. (Press Stop if that happens.)
    Vocabulary
    English
    infinite loop/ˈɪnfɪnət luːp/
    trace table/treɪs ˈteɪbl/
    5.3

    for...of, break & continue

    for...of visits every item of an array (or every character of a string) in turn, with no index to manage:

    const fruits = ["apple", "kiwi", "plum"];
    for (const fruit of fruits) {
      console.log(fruit.toUpperCase());
    }
    // APPLE
    // KIWI
    // PLUM
    

    break leaves a loop at once; continue skips the rest of this pass and goes on to the next one:

    const marks = [55, 80, -1, 90];
    let sum = 0;
    for (const m of marks) {
      if (m < 0) {
        break;            // -1 means "end of the data"
      }
      if (m < 60) {
        continue;         // skip a fail, keep looping
      }
      sum += m;
    }
    console.log(sum);     // 80
    

    Common mistakes

    • An off-by-one error: i < 3 runs for 0, 1, 2; i <= 3 runs one more time. Count the passes.
    • Starting the total inside the loop: let total = 0; must come before the loop, or it is reset every pass.
    • A while loop runs for ever if its condition stays true and no exit is reached.
  • 6 Functions
    6.1

    Parameters & return

    A function 函数 is a reusable piece of code. A function declaration gives it a name, which you can use to call 调用 it:

    function greet(name) {
      return `Hello, ${name}!`;
    }
    
    console.log(greet("Mei"));   // Hello, Mei!
    console.log(greet("Tom"));   // Hello, Tom!
    
    • name is a parameter 参数: a variable that receives a value when the function is called.
    • "Mei" is the argument 实参: the actual value passed in.
    • return sends a value back to the caller and ends the function at once.

    A regular function that reaches its end without returning a value gives back undefined. So return the answer, and let the caller decide whether to print it:

    function area(width, height) {
      return width * height;
    }
    
    const a = area(4, 3);
    console.log(a + 1);          // 13  (a returned value can be used again)
    

    A parameter can have a default value, used when the caller leaves it out. A return near the top can also stop early when the input is wrong:

    function price(amount, taxRate = 0.1) {
      if (amount < 0) {
        return "invalid";        // stop early: nothing below runs
      }
      return (amount * (1 + taxRate)).toFixed(2);
    }
    
    console.log(price(20));      // 22.00  (taxRate is 0.1)
    console.log(price(20, 0));   // 20.00
    console.log(price(-5));      // invalid
    

    Small functions can call each other. Each does one job, so each is easy to test:

    function average(list) {
      let sum = 0;
      for (const x of list) sum += x;
      return sum / list.length;
    }
    
    function report(name, marks) {
      const avg = average(marks);
      const result = avg >= 50 ? "pass" : "fail";
      return `${name}: ${avg.toFixed(1)} (${result})`;
    }
    
    console.log(report("Mei", [62, 48, 71]));   // Mei: 60.3 (pass)
    

    Practice

    Write each function on paper first, then open the model answer, compare, and press Run.

    1. Celsius to Fahrenheit. Write toFahrenheit(c), which returns c × 9 ÷ 5 + 32. Log the answers for 0 and 100.

    Model answer
    function toFahrenheit(c) {
      return c * 9 / 5 + 32;
    }
    
    console.log(toFahrenheit(0));     // 32
    console.log(toFahrenheit(100));   // 212
    

    The formula goes after return, so each call stands for its answer.

    2. The largest of three. Write max2(a, b), then use it twice inside max3(a, b, c).

    Model answer
    function max2(a, b) {
      return a > b ? a : b;
    }
    
    function max3(a, b, c) {
      return max2(max2(a, b), c);
    }
    
    console.log(max3(4, 9, 7));    // 9
    console.log(max3(8, 2, 8));    // 8
    

    The inner call finds the larger of a and b; the outer call compares that with c. Small functions joined together are easier to test than one long one.

    3. A valid age. Write isValidAge(age), which returns true only for a whole number from 0 to 120. Test 15, -3, 12.5 and 130.

    Model answer
    function isValidAge(age) {
      return Number.isInteger(age) && age >= 0 && age <= 120;
    }
    
    for (const a of [15, -3, 12.5, 130]) {
      console.log(a, isValidAge(a));
    }
    // 15 true
    // -3 false
    // 12.5 false
    // 130 false
    

    Each && adds one rule, and all of them must hold. Test one value that breaks each rule, not only a good one.

    Vocabulary
    English
    function/ˈfʌŋkʃn/
    call/kɔːl/
    parameter/pəˈræmɪtə/
    argument/ˈɑːɡjuːmənt/
    6.2

    Arrow functions

    An arrow function 箭头函数 is a shorter way to write a function. Store it in a const:

    const square = (n) => n * n;
    const add = (a, b) => a + b;
    
    console.log(square(5));      // 25
    console.log(add(2, 3));      // 5
    
    • With one expression after =>, its value is returned without writing return.
    • With curly braces you need return again:
    const grade = (mark) => {
      if (mark >= 50) {
        return "pass";
      }
      return "fail";
    };
    console.log(grade(64));      // pass
    

    Arrow functions are often passed to other functions, as you will see with map and filter in topic 7.

    Vocabulary
    English
    arrow function
    6.3

    Scope

    The scope 作用域 of a variable is the part of the code that can see it. A variable made with let or const inside { } is accessible in that block and its nested scopes. A nested function can keep access after the outer call returns:

    const level = "global";
    
    function show() {
      const inside = "local";
      console.log(level);        // global  (outer variables are visible)
      console.log(inside);       // local
    }
    
    show();
    console.log(typeof inside);  // undefined  (inside does not exist out here)
    
    • A variable made inside a function is a local variable 局部变量; each call gets a fresh one.

    The same is true for any block: a let or const made inside the { } of a loop or an if ends with that block. Make the variable before the block if you need it afterwards, as total is here:

    let total = 0;
    for (let i = 1; i <= 3; i++) {
      const square = i * i;      // square exists only inside the { }
      total += square;
    }
    console.log(total);          // 14
    console.log(typeof square);  // undefined  (it ended with the loop)
    
    • Using square after the loop, as in console.log(square), stops the program with ReferenceError: square is not defined.

    A function made inside another function keeps the outer variables, even after the outer call has finished. This is a closure 闭包. Each counter below has its own count:

    function makeCounter() {
      let count = 0;
      return () => {
        count = count + 1;
        return count;
      };
    }
    
    const clicks = makeCounter();
    const visits = makeCounter();
    console.log(clicks());       // 1
    console.log(clicks());       // 2
    console.log(visits());       // 1  (a separate count)
    
    • Pass values in as parameters and get results out with return, instead of changing outer variables from inside a function.

    Common mistakes

    • Forgetting return: the function works out the answer, then gives back undefined.
    • Calling without brackets: greet is the function itself; greet("Mei") runs it.
    • Printing inside the function and printing its result prints twice, or prints undefined.
    • An arrow function with braces and no return: (n) => { n * n } gives undefined. Write (n) => n * n or add return.
    • Calling a const arrow function before the line that makes it fails with ReferenceError; a function declaration can be called earlier in the file.
    Vocabulary
    English
    scope/skəʊp/
    local variable/ˈləʊkl ˈveərɪəbl/
    closure/ˈkləʊʒə/
  • 7 Arrays
    7.1

    Making & changing arrays

    An array 数组 holds a list of values in order, inside square brackets. Each item is an element 元素, and the first index is 0:

    const scores = [72, 88, 95];
    console.log(scores[0]);        // 72
    console.log(scores.length);    // 3
    scores[1] = 90;                // change one element
    console.log(scores);           // [72,90,95]
    
    • const stops you giving scores a whole new array, but you can still change what is inside it.
    • Reading past the end gives undefined: scores[3] is undefined.

    Add and remove at the end with push and pop:

    const queue = ["Ann", "Ben"];
    queue.push("Cai");             // add to the end
    console.log(queue);            // ["Ann","Ben","Cai"]
    const last = queue.pop();      // remove from the end and return it
    console.log(last);             // Cai
    console.log(queue.length);     // 2
    

    An array can hold arrays. That makes a grid, read with two indexes, row first:

    const grid = [
      [1, 2, 3],
      [4, 5, 6],
    ];
    console.log(grid[1][2]);       // 6  (row 1, column 2)
    

    To visit every element, use a for...of loop. It gives you each value in turn, so you need no index:

    const marks = [12, 7, 15];
    let total = 0;
    for (const m of marks) {
      total += m;
    }
    console.log(total);            // 34
    

    An array variable holds a reference 引用 to the array, not a copy. const b = a gives the same array a second name, so a change through b also shows in a. Use [...a] when you want a real copy:

    const a = [1, 2, 3];
    const b = a;                   // same array, two names
    b.push(4);
    console.log(a);                // [1,2,3,4]
    
    const c = [...a];              // a new array with the same values
    c.push(5);
    console.log(a.length, c.length);   // 4 5
    

    Two more methods you will use often: slice copies part of an array, and join turns it into one string.

    const words = ["red", "green", "blue"];
    console.log(words.slice(0, 2));     // ["red","green"]  (stops before index 2)
    console.log(words.join(" - "));     // red - green - blue
    
    Vocabulary
    English
    array/əˈreɪ/
    element/ˈelɪmənt/
    reference/ˈrefrəns/
    7.2

    map, filter & reduce

    These methods take a function and apply it to the array elements. They return a new array (or value) without themselves replacing the original items. The function you pass in can still change the original array or its objects:

    • map makes a new array by changing every element.
    • filter keeps only the elements for which the function returns true.
    • reduce combines all the elements into one value, such as a total.
    const prices = [4, 10, 25];
    const withTax = prices.map((p) => p * 1.1);
    console.log(withTax.map((p) => p.toFixed(2)));   // ["4.40","11.00","27.50"]
    
    const cheap = prices.filter((p) => p < 20);
    console.log(cheap);                              // [4,10]
    
    const total = prices.reduce((sum, p) => sum + p, 0);
    console.log(total);                              // 39
    

    In reduce, sum is the accumulator 累加器. It starts at the last argument (0) and takes the function's result after each element. For [3, 8, 5].reduce((sum, n) => sum + n, 0):

    Element n sum before sum + n (the new sum)
    3 0 3
    8 3 11
    5 11 16

    The result is the last sum, 16.

    You can chain 链式调用 these methods: each one works on the array that the one before it returned. Read the chain from left to right:

    const scores = [55, 82, 47, 91, 68];
    const passed = scores
      .filter((s) => s >= 50)    // [55,82,91,68]
      .map((s) => s + 5);        // add 5 bonus points
    console.log(passed);         // [60,87,96,73]
    

    Practice

    Each task has one line of work: choose map, filter or reduce. Write it on paper first, then open the model answer, compare, and press Run.

    1. Prices with tax. const prices = [10, 25, 4]; Make a new array with 20% tax added to each price.

    Model answer
    const prices = [10, 25, 4];
    const withTax = prices.map((p) => p * 1.2);
    console.log(withTax);        // [12,30,4.8]
    

    map: one new value for each old one, so the new array has the same length.

    2. Names that start with A. const names = ["Ana", "Ben", "Aisha", "Carl"]; Keep only the names that start with "A".

    Model answer
    const names = ["Ana", "Ben", "Aisha", "Carl"];
    const aNames = names.filter((n) => n.startsWith("A"));
    console.log(aNames);         // ["Ana","Aisha"]
    

    filter: the function answers yes or no for each item, and only the yes items are kept.

    3. The longest word's length. const words = ["sun", "planet", "moon"]; Find the length of the longest word.

    Model answer
    const words = ["sun", "planet", "moon"];
    const longest = words.reduce((best, w) => Math.max(best, w.length), 0);
    console.log(longest);        // 6
    

    reduce: many items become one value. best starts at 0 and keeps the larger of itself and each word's length. words.map((w) => w.length) then Math.max(...) also works.

    Vocabulary
    English
    accumulator/əˈkjuːmjʊleɪtə/
    chain
    7.3

    Searching & sorting

    sort() with no compare function sorts numbers as text
    Method Gives back Example with [5, 8, 2] Result
    .includes(x) true or false .includes(8) true
    .indexOf(x) the first index of x, or -1 .indexOf(2) 2
    .find(f) the first element where f is true .find((n) => n > 6) 8
    .findIndex(f) its index, or -1 .findIndex((n) => n > 6) 1

    sort puts the elements in order. With no function, it sorts them as text, so numbers come out in the wrong order:

    const nums = [10, 9, 100, 1];
    console.log([...nums].sort());                   // [1,10,100,9]   (as text!)
    console.log([...nums].sort((a, b) => a - b));    // [1,9,10,100]
    console.log([...nums].sort((a, b) => b - a));    // [100,10,9,1]
    
    • The compare function returns a negative number when a should come first, and a positive number when b should.
    • sort changes the array itself. [...nums] makes a copy first, so nums keeps its order.

    To sort objects, compare one of their properties. Subtract numbers; for text, use localeCompare, which returns a negative or positive number in the same way:

    const people = [
      { name: "Ann", age: 15 },
      { name: "Ben", age: 12 },
      { name: "Cai", age: 14 },
    ];
    const byAge = [...people].sort((x, y) => x.age - y.age);
    console.log(byAge.map((p) => p.name));     // ["Ben","Cai","Ann"]
    
    const byName = [...people].sort((x, y) => x.name.localeCompare(y.name));
    console.log(byName[0].name);               // Ann
    

    Common mistakes

    • The last element is arr[arr.length - 1], not arr[arr.length].
    • map and filter do not change the array: store their result.
    • nums.sort() on numbers sorts them as text. Pass (a, b) => a - b.
    • const b = a does not copy an array. Change b and a changes too; copy with [...a].
    • reduce without a start value uses the first element instead. Give the start value (0 for a total) every time.
  • 8 Objects
    8.1

    Objects & properties

    An object 对象 groups related values under names. Each name-and-value pair is a property 属性. The name is called the key 键:

    const pupil = {
      name: "Mei",
      age: 17,
      form: "11A",
    };
    console.log(pupil.name);       // Mei
    console.log(pupil["form"]);    // 11A  (bracket form, with the key as a string)
    
    • Read a property with a dot (pupil.age) or with brackets (pupil["age"]). Use brackets when the key is in a variable: pupil[field].
    • A key that does not exist gives undefined.

    Change a property, or add a new one, by assigning to it:

    const pupil = { name: "Mei", age: 17 };
    pupil.age = 18;                // change
    pupil.house = "Red";           // add
    console.log(pupil);            // {"name":"Mei","age":18,"house":"Red"}
    

    Two names, one object. const b = a; does not copy an object: both names point to the same object, so a change through one name shows through the other. Make a real copy with { ...a }:

    const a = { name: "Mei", mark: 88 };
    const b = a;              // same object, second name
    const c = { ...a };       // a new object with the same properties
    b.mark = 50;
    console.log(a.mark);      // 50  (changed through b!)
    console.log(c.mark);      // 88  (the copy is separate)
    console.log(a === b);     // true   (same object)
    console.log(a === c);     // false  (different objects, even with equal contents)
    

    A property can hold a function. It is then a method, and this inside it means the object it was called on:

    const account = {
      owner: "Sam",
      balance: 40,
      pay(amount) {
        if (amount > this.balance) {
          return "not enough money";
        }
        this.balance -= amount;
        return `paid ${amount}, ${this.balance} left`;
      },
    };
    console.log(account.pay(15));   // paid 15, 25 left
    console.log(account.pay(30));   // not enough money
    

    Classes: many objects of the same shape

    When you need many objects with the same properties and methods, write a class 类 once. The constructor 构造函数 runs when you write new, and sets each new object's properties through this:

    class Account {
      constructor(owner, balance) {
        this.owner = owner;
        this.balance = balance;
      }
      pay(amount) {
        if (amount > this.balance) {
          return "not enough money";
        }
        this.balance -= amount;
        return `${this.owner} paid ${amount}, ${this.balance} left`;
      }
    }
    
    const sam = new Account("Sam", 40);
    const mei = new Account("Mei", 100);
    console.log(sam.pay(15));   // Sam paid 15, 25 left
    console.log(mei.pay(15));   // Mei paid 15, 85 left
    console.log(sam.balance);   // 25: each object keeps its own balance
    
    • Methods inside a class have no function word and no commas between them.
    • Forgetting new stops the program: Account("Sam", 40) gives a TypeError.
    Vocabulary
    English
    object/ˈɒbdʒekt/
    property
    key/kiː/
    class/klæs/
    constructor/kənˈstrʌktə/
    8.2

    Arrays of objects

    A list of records 记录 is an array of objects. Combine it with the array methods from topic 7:

    const pupils = [
      { name: "Mei", mark: 88 },
      { name: "Tom", mark: 64 },
      { name: "Sara", mark: 95 },
    ];
    
    const passed = pupils.filter((p) => p.mark >= 70);
    console.log(passed.map((p) => p.name));            // ["Mei","Sara"]
    
    const best = [...pupils].sort((a, b) => b.mark - a.mark)[0];
    console.log(`${best.name} has the top mark`);       // Sara has the top mark
    

    To total a property, use reduce or a loop:

    const pupils = [{ mark: 88 }, { mark: 64 }, { mark: 95 }];
    let sum = 0;
    for (const p of pupils) {
      sum += p.mark;
    }
    console.log((sum / pupils.length).toFixed(1));      // 82.3
    
    Vocabulary
    English
    record/ˈrekɔːd/
    8.3

    Looping over an object

    Object.keys gives an array of the keys, and Object.entries gives [key, value] pairs, so you can loop over them:

    const stock = { pens: 12, rulers: 0, books: 5 };
    
    console.log(Object.keys(stock));             // ["pens","rulers","books"]
    
    for (const [item, count] of Object.entries(stock)) {
      if (count === 0) {
        console.log(`${item}: sold out`);
      }
    }
    // rulers: sold out
    

    An object is a good counter 计数器: use each thing you count as a key.

    const words = ["red", "blue", "red", "red"];
    const counts = {};
    for (const w of words) {
      counts[w] = (counts[w] || 0) + 1;   // 0 the first time the key is seen
    }
    console.log(counts);                  // {"red":3,"blue":1}
    

    Common mistakes

    • pupil.field looks for a key called field. When the key is in a variable, write pupil[field].
    • A comma goes between properties, not a semicolon: { name: "Mei", age: 17 }.
    • for...of cannot loop over an object directly. Loop over Object.keys(...) or Object.entries(...).
    • === on two objects asks "the same object?", not "the same contents?": { x: 1 } === { x: 1 } is false.
    • { ...a } copies one level only: an array or object inside a is still shared.
    Vocabulary
    English
    counter/ˈkaʊntə/
  • 9 Errors
    9.1

    Reading error messages

    When JavaScript cannot carry on, it stops and shows an error 错误. The first word names the kind of error; the rest says what went wrong and where. Read it, then look at the line it names.

    SyntaxError: missing ) after argument list
    ReferenceError: totl is not defined
    TypeError: Cannot read properties of undefined (reading 'length')
    
    The TypeError message split into two parts: the error name, then what went wrong, that .length was used on undefined
    First the kind of error, then what went wrong.
    Error What it means A typical cause
    SyntaxError the code is not written correctly, so nothing runs a missing bracket or quote
    ReferenceError a name that does not exist a spelling mistake 拼写错误: totl for total
    TypeError the value is the wrong type for what you did using .length on undefined

    The exact wording can differ between browsers, but the name of the error is the same. This program catches each error so that it can print its name:

    try {
      const total = 5;
      console.log(totl);
    } catch (e) {
      console.log(e.name);           // ReferenceError
    }
    
    try {
      const pupil = undefined;
      console.log(pupil.length);
    } catch (e) {
      console.log(e.name);           // TypeError
    }
    

    Some mistakes give no error at all, just a wrong answer: a logic error 逻辑错误. To find one, print the values along the way with console.log, and check them by hand.

    This average of 4, 6 and 8 should be 6, but the program prints 4.67. One console.log inside the loop shows why:

    function average(list) {
      let sum = 0;
      for (let i = 1; i < list.length; i++) {
        console.log("i =", i, "adding", list[i]);
        sum += list[i];
      }
      return sum / list.length;
    }
    console.log(average([4, 6, 8]));
    // i = 1 adding 6
    // i = 2 adding 8
    // 4.666666666666667
    

    The loop never adds list[0], the 4: it starts at i = 1. Change it to let i = 0 and the answer is 6. Remove the extra console.log once the bug is fixed.

    Vocabulary
    English
    error/ˈerə/
    spelling mistake
    logic error/ˈlɒdʒɪk ˈerə/
    9.2

    try, catch & throw

    Code that might fail goes in a try block. If an error happens there, JavaScript jumps to catch instead of stopping, and e holds the error:

    try {
      JSON.parse("{not valid}");
      console.log("parsed");         // skipped
    } catch (e) {
      console.log("Could not read the data");
    }
    console.log("The program carries on");
    
    Flow from a try block: with no error the rest of try runs; with an error the rest is skipped and catch runs; both paths reach the line after
    Either way, the program reaches the line after catch.

    Your own code can raise an error with throw. This lets a function refuse bad input 输入 clearly, instead of returning a wrong answer:

    function average(list) {
      if (list.length === 0) {
        throw new Error("the list is empty");
      }
      return list.reduce((s, x) => s + x, 0) / list.length;
    }
    
    console.log(average([4, 6]));    // 5
    try {
      average([]);
    } catch (e) {
      console.log(`Error: ${e.message}`);   // Error: the list is empty
    }
    
    • new Error("…") makes an error whose message is your text.

    A finally block runs at the end in both cases, error or not. It is the place for work that must always happen:

    function readAge(text) {
      try {
        const n = Number(text);
        if (Number.isNaN(n)) {
          throw new Error(`"${text}" is not a number`);
        }
        return n;
      } catch (e) {
        console.log(e.message);
        return null;
      } finally {
        console.log("checked", text);
      }
    }
    console.log(readAge("15"));    // checked 15, then 15
    console.log(readAge("abc"));   // "abc" is not a number, checked abc, then null
    
    • Only use try around code that can really fail, such as reading data. Do not use it to hide mistakes in your own code.

    Common mistakes

    • Skipping the message. Its first line names the kind of error and what went wrong; start there.
    • A catch that does nothing (catch (e) {}) hides the problem: at least print e.message.
    • throw "text" works, but throw new Error("text") also records where the error happened.
    Vocabulary
    English
    input/ˈɪnpʊt/

Log in or create account

IGCSE, A-Level & AP