Skip to content
BetaDE
Lesson 5 of 11JavaScript

JavaScript · Lesson 5 · 30 minutes

Functions

What you'll learn

  • Write functions with function
  • Return values with return
  • Use arrow functions (=>)

Building a function

function greet(name) {
  console.log(`Hello ${name}!`);
}

greet("Mia");
greet("Tom");

A function is a mini program with a name: write it once, use it as often as you like.

Results with return

function square(number) {
  return number * number;
}

const result = square(7);
console.log(result);
console.log(square(2) + square(3));

Python comparison: def square(number): becomes function square(number) { … }.

Arrow functions

In JavaScript, short functions are often written as arrow functions:

const halve = (x) => x / 2;
const plus = (a, b) => a + b;

console.log(halve(10));
console.log(plus(2, 3));

(x) => x / 2 means: “take x and return x / 2”. You’ve already used exactly this with filter and map.

Quick check

What does this program print?

const times3 = (n) => n * 3;
function plus1(n) {
  return n + 1;
}
console.log(times3(plus1(2)));

Your task

Your turn

Write the function area(width, height) that returns the area of a rectangle. Also write an arrow function const double = (x) => … that doubles its number. Print double(area(3, 4)).

function area(width, height) {
}

// const double = ...

Solve it without hints to earn a ⭐ on your progress page.

Show solution

Try it yourself first – mistakes teach you the most. Here is one possible solution:

function area(width, height) {
  return width * height;
}

const double = (x) => x * 2;

console.log(double(area(3, 4)));