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):becomesfunction 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 = ...- Something to think about
Inside the function, return width
*height; - Which command helps?
constdouble=(x)=>x*2; - Gap code – fill in the ___
function area(width, height) { return ___; } const double = ___; console.log(___);
Solve it without hints to earn a ⭐ on your progress page.
Show solution🔒 Unlocks after all hints or 2 checks
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)));