Functions & arrow functions

Computer Science · JavaScript

Question 1 of 10

0

    What does this JavaScript code log? const scale = (x) => x * 2 + 6; console.log(scale(8));

    Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.

    How to type your answer
    • Fractions: 3/4. Mixed numbers: 1 1/2.
    • Decimals with a point or a comma: 0.75 or 0,75.
    • Negative numbers start with a minus: -3/4.
    • Percentages need the % sign: 75%.

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Functions & arrow functions explained

    A function groups code under a name so it can be reused with different inputs. JavaScript has function declarations, function expressions and the shorter arrow function syntax.

    A function declaration starts with the keyword function and a name. Declarations are hoisted, so they can be called before the line where they appear. A function expression stores a function in a variable and is usable only after that line.

    An arrow function uses => instead of the function keyword. When the body is a single expression, its value is returned automatically. With braces, the function must use return explicitly, or it returns undefined.

    const add = (a, b) => a + b;
    function square(n = 2) {
        return n * n;
    }
    console.log(add(3, 4), square(), square(5));
    

    Parameters can have default values, used when the argument is missing or undefined. Extra arguments are ignored. Arrow functions do not have their own this, which matters for object methods.

    Worked example

    add(3, 4) returns 7. square() uses the default n = 2, so it returns 4. square(5) returns 25. The program prints 7, 4 and 25 on one line.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What does this JavaScript code log?

      const scale = (x) => x * 4 + 5; console.log(scale(9));

    • Medium

      What does this JavaScript code log?

      const f = (x, y = x * 5) => x + y; console.log(f(9));

    • Hard

      What does this JavaScript code log?

      let base = 15; const add = (x = base) => x + base; const make = () => { let c = 0; return () => ++c; }; const next = make(); next(); base = 19; console.log(add() + next() * 8);