Defining Functions
In this lesson, you will learn to write your own functions. Let's start with a problem: we need the areas of three rectangles. The area of a rectangle is its width times its height, so we could write:
const width1 = 5;
const height1 = 6;
const area1 = width1 * height1;
console.log(area1);
const width2 = 10;
const height2 = 5;
const area2 = width2 * height2;
console.log(area2);
const width3 = 1;
const height3 = 5;
const area3 = width3 * height3;
console.log(area3);This prints:
30
50
5It works, but we wrote the same three lines three times, and only the numbers changed. Imagine a hundred rectangles! And if we found a mistake in the calculation, we would have to fix it in a hundred places.
Programmers try not to repeat code. Instead, they write the repeated part once, give it a name and then use it wherever they need it. Such a named piece of code is called a function.
You have already used functions that come with JavaScript: methods such as console.log() and .push() are functions too. Now you will write your own. Creating a function is called defining it:
function sayHello() {
console.log("Hello!");
console.log("Have a nice day!");
}A function definition has four parts:
- The keyword
function, which tells JavaScript that a function follows. - The name of the function, here
sayHello. It follows the same rules as variable names: no spaces, and names made of several words are written in camelCase. A function does something, so its name usually starts with a verb, such assayHelloorprintArea. - Parentheses
(). They are empty for now; you will soon find out what goes in them. - A block of code in curly braces
{ }, called the body of the function. It holds the commands the function runs. We indent them by 4 spaces, so that it's easy to see they belong to the function. As withif, there is no semicolon after the closing}.
When you run this code, nothing is printed. That's not a mistake! A definition only tells JavaScript what the function should do, like a recipe written down in a cookbook: nobody has cooked anything yet. In the next exercise, you will make the function run.
A common mistake is forgetting the parentheses after the name. function sayHello { ends with the error SyntaxError: Unexpected token '{': JavaScript expected ( after the name, but found {.
Instructions
Create a function named firstFunction whose body prints This is my first function! with console.log(). Then run the program: nothing is printed yet, and that's how it should be.
Start programming for free
1/10