Functions
As your code grows, you'll notice yourself writing the same few lines in several places. Functions let you write those lines once, give them a name and use them as many times as you like. They're one of the most important ideas in all of programming.
Your first function
Here's a function that prints a greeting:
function sayHello() {
console.log('Hello!');
}This defines the function. It doesn't run anything yet. It's like writing down a recipe without cooking it.
To run it, you call the function by writing its name followed by parentheses:
sayHello(); sayHello();
Now it prints "Hello!" twice. You've already been calling functions all along. console.log() is a function someone else wrote for you.
Parameters: giving a function input
A function that always does exactly the same thing is a bit limited. Parameters let you pass information in:
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet('Alex'); // Hello, Alex!
greet('Sam'); // Hello, Sam!name is the parameter. It works like a variable that only exists inside the function, and it gets whatever value you pass in when you call it. The value you pass in, like 'Alex', is called an argument.
A function can have several parameters, separated by commas:
function introduce(name, city) {
console.log(`I'm ${name} and I live in ${city}.`);
}
introduce('Alex', 'Malmö');The order matters. The first argument goes to the first parameter and so on.
In greet('Sam'), what is 'Sam'?
Select one answer
Return values: getting something back
So far our functions print things. Often you want a function to calculate something and give the result back, so you can use it elsewhere. That's what return does:
function add(a, b) {
return a + b;
}
const sum = add(2, 3);
console.log(sum); // 5When JavaScript reaches return, the function stops and hands the value back to wherever it was called. You can store it in a variable, use it in a condition or pass it to another function.
Here's the difference between printing and returning, which confuses a lot of beginners: console.log shows something to you, the developer. return hands a value back to your code, so the rest of your program can use it.
function formatPrice(amount) {
return `${amount} kr`;
}
const label = formatPrice(99); // '99 kr'What does return do?
Select one answer
Arrow functions
There's a shorter way to write functions that you'll see everywhere in modern JavaScript, called arrow functions:
const add = (a, b) => {
return a + b;
};When the function only returns a single value, you can make it even shorter by leaving out the curly braces and the word return:
const add = (a, b) => a + b; const double = (n) => n * 2;
Both styles do the same job. Regular functions with the function keyword are often a bit clearer while you're learning. Arrow functions really shine when you pass a small function to another function, which you'll do a lot in the next lessons.
Scope: where variables live
A variable created inside a function only exists inside that function. This is called scope:
function makeMessage() {
const message = 'Hi!';
return message;
}
console.log(message); // error: message is not definedThat's actually a good thing. It means variables inside different functions can't accidentally interfere with each other, even if they have the same name.
When to make a function
A good rule of thumb: if you've written the same code twice, consider turning it into a function. And if a piece of code does one clear job, like formatting a date or checking a form, giving it a name as a function makes your program much easier to read.
Good function names usually start with a verb that says what they do: calculateTotal, showMessage, isValidEmail.
Which name is the best fit for a function that checks if a password is long enough?
Select one answer
Write a few functions in script.js:
- A function
greet(name)that returns a greeting string, like "Hello, Alex!", and log what it returns - A function
calculateAge(birthYear)that returns an age based on the current year. Tip:new Date().getFullYear()gives you the current year - A function
isAdult(age)that returnstrueif the age is 18 or more andfalseotherwise - Rewrite one of them as an arrow function
Use them together: calculate your age, then use isAdult in an if statement to log a message.