Introduction to Functions
In this chapter, we will get acquainted with functions in JavaScript. Imagine that you need to calculate the area of three rectangles. For this, we need their width and height and multiply them. We could perform this with the following code:
const width1 = 5;
const height1 = 6;
const area1 = width1 * height1;
console.log(area1); // Prints 30
const width2 = 10;
const height2 = 5;
const area2 = width2 * height2;
console.log(area2); // Prints 50
const width3 = 1;
const height3 = 5;
const area3 = width3 * height3;
console.log(area3); // Prints 5
This is tedious, and you can certainly imagine that calculating the area of 100 rectangles this way is madness.
In programming, we usually try to avoid repeating the same code multiple times. Instead, we can group the part of the code that repeats and reuse it. We achieve this with functions. A function is a reusable part of the code that solves a specific problem.
Instructions
When you're ready, move on to the next exercise!
Start programming for free
1/7