Writing Functions
Reusable blocks of code with inputs
A function is a named block of code that does a job. You write it once, then call it whenever you need that job done. This saves you from repeating yourself.
Defining a function
function sayHello() {
console.log("Hello there!");
}
sayHello(); // this runs the functionThe word function starts the definition, sayHello is the name, the ( ) hold inputs (none yet), and the code lives inside the { }. Writing sayHello() on its own line calls the function, telling it to run.
Giving a function inputs
Functions become really useful when you pass them information. These inputs are called parameters.
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Alex");
greet("Sam");The same function now greets anyone you give it.
Getting an answer back
A function can hand a value back to you using return. You can then store or print that result.
function add(a, b) {
return a + b;
}
let sum = add(3, 4);
console.log(sum); // 7Try it yourself
Call the functions with different inputs and see what comes back.
Press “Run code” to see the result.
Quick check
Q1 What does calling a function mean?
Q2 What does the return keyword do?
Want to save your progress? It's free.
Create a free account