Skip to content
Laviyx Learn

Try

JavaScript Functions Practice

Practise writing functions, default and rest parameters, arrow functions, callbacks and closures. Every solution has been run with Node.js and shows its real output.

Intermediate6 problemsUpdated

Review first: Functions, Parameters, Defaults and Rest, Arrow Functions, Closures, Callbacks and Higher-Order Functions

  1. 1.Default parameters

    Beginner

    Write greet(name = "friend", greeting = "Hello") that returns "Hello, friend!" style strings. Print the result with no arguments, with "Asha", and with "Asha" and "Namaste".

    Show hint

    Defaults are written in the parameter list. Return a template literal.

    Show solution
    JavaScript
    function greet(name = "friend", greeting = "Hello") {
      return `${greeting}, ${name}!`;
    }
    console.log(greet());
    console.log(greet("Asha"));
    console.log(greet("Asha", "Namaste"));
    Output
    Hello, friend!
    Hello, Asha!
    Namaste, Asha!
  2. 2.Average of any number of values

    Beginner

    Write average(...numbers) that returns the average of its arguments, or 0 if there are none. Print average(80, 90, 70) and average().

    Show hint

    A rest parameter collects the arguments into an array. Use reduce for the sum.

    Show solution
    JavaScript
    function average(...numbers) {
      if (numbers.length === 0) return 0;
      return numbers.reduce((sum, n) => sum + n, 0) / numbers.length;
    }
    console.log(average(80, 90, 70), average());
    Output
    80 0
  3. 3.A counter with a closure

    Intermediate

    Write makeCounter(start = 0) that returns an object with increment(), decrement() and value() methods, keeping the count private. Create two counters, change them independently, and print both values.

    Show hint

    Declare let count = start inside makeCounter and return functions that use it.

    Show solution
    JavaScript
    function makeCounter(start = 0) {
      let count = start;
      return {
        increment: () => ++count,
        decrement: () => --count,
        value: () => count,
      };
    }
    const a = makeCounter();
    const b = makeCounter(10);
    a.increment();
    a.increment();
    b.decrement();
    console.log(a.value(), b.value());
    Output
    2 9
  4. 4.A higher-order function

    Intermediate

    Write applyTimes(fn, times, value) that calls fn on value repeatedly (times times) and returns the result. Use it to double 3 four times, and to add "!" to "Hi" three times.

    Show hint

    Loop times times, replacing the value with fn(value) each time.

    Show solution
    JavaScript
    function applyTimes(fn, times, value) {
      let result = value;
      for (let i = 0; i < times; i++) result = fn(result);
      return result;
    }
    console.log(applyTimes((n) => n * 2, 4, 3));
    console.log(applyTimes((s) => s + "!", 3, "Hi"));
    Output
    48
    Hi!!!
  5. 5.Run a function only once

    Intermediate

    Write once(fn) that returns a new function which calls fn the first time and returns the same first result on every later call. Test it with a function that logs "Initialising" and returns 42.

    Show hint

    Use a closure with a called flag and a stored result.

    Show solution
    JavaScript
    function once(fn) {
      let called = false;
      let result;
      return (...args) => {
        if (!called) {
          called = true;
          result = fn(...args);
        }
        return result;
      };
    }
    const init = once(() => {
      console.log("Initialising");
      return 42;
    });
    console.log(init(), init(), init());
    Output
    Initialising
    42 42 42
  6. 6.Compose small functions

    Intermediate

    Write pipe(...fns) that returns a function passing its input through each function from left to right. Use it to build slugify from three steps: trim, lowercase, and replace spaces with hyphens. Print slugify(" Learn JavaScript Fast ").

    Show hint

    fns.reduce((acc, fn) => fn(acc), value) runs the functions in order.

    Show solution
    JavaScript
    const pipe = (...fns) => (value) => fns.reduce((acc, fn) => fn(acc), value);
    const slugify = pipe(
      (s) => s.trim(),
      (s) => s.toLowerCase(),
      (s) => s.replaceAll(" ", "-"),
    );
    console.log(slugify("  Learn JavaScript Fast "));
    Output
    learn-javascript-fast