Making and calling a function
You make a function with the word function, a name, brackets and curly braces. The code inside doesn't run until you call the function by writing its name followed by brackets.
function sayHi() {
console.log("Hi!");
}
sayHi();
sayHi();Hi! Hi!
Parameters
Parameters are names in the brackets that receive values when the function is called. The values you pass in are called arguments.
function greet(name) {
console.log("Hi, " + name);
}
greet("Sam");
greet("Ana");Hi, Sam Hi, Ana
Returning a value
return sends a value back to wherever the function was called. You can store it, print it or use it in another calculation.
function double(n) {
return n * 2;
}
let x = double(4);
console.log(x + 1);9
Try it
What does this print?
function addOne(n) {
return n + 1;
}
console.log(addOne(addOne(2)));
return ends the function
As soon as a function reaches return, it stops. Any lines after it inside the function are skipped.
Try it
What does this print?
function test() {
return "hi";
console.log("bye");
}
console.log(test());
Printing is not returning
This is one of the most common beginner mix-ups. console.log inside a function shows a value on screen, but the function still gives back nothing. In JavaScript, nothing is called undefined.
function add(a, b) {
console.log(a + b);
}
let result = add(2, 3);
console.log(result);5 undefined
Try it
How do you fix the add function above so result is 5?
Arrow functions
You'll often see a shorter way to write small functions, called an arrow function. These two do the same thing.
function square(n) {
return n * n;
}
const square2 = (n) => n * n;
console.log(square(5), square2(5));25 25
Common mistakes
greet on its own does nothing. You need greet() to run it.
If a function calculates something but never returns it, you get undefined back.
Arguments match parameters by position. If a function is subtract(a, b), then subtract(2, 10) is -8, not 8.
Recap
- A function is a named block of code you can run again.
- Parameters receive the values you pass in.
- return sends a value back and ends the function.
- console.log shows a value. It doesn't return it.