The code that adds up a shopping total is finished, and it is five lines long. Three places need it: the cart page, the checkout page and the receipt. If you copy those five lines into three places and then find a mistake, you have to fix it three times.
A function solves that problem. A function is a named block of code that you write once and can then call (run) again and again. You send something in, the function works on it, then the function gives back a result. A function is like a blender. The fruit you put in is the input, the juice that comes out is the result, and the same blender works for any fruit.
Making and calling a function
This code makes the function greeting, then calls it twice:
function greeting(name) {
return "Good morning, " + name + "!";
}
console.log(greeting("Budi")); // Good morning, Budi!
console.log(greeting("Sari")); // Good morning, Sari!
functionis the keyword that makes a function, andgreetingis the function's name.(name)is a parameter: a name for the value that is sent in when the function is called. Think of a parameter as a variable whose value comes from outside the function.- From
{to}is the function's body: the code that runs every time the function is called. returngives the result back to the place where the function was called.greeting("Budi")calls the function."Budi"is the argument: the value sent to the function. That value goes into the parametername.
Writing a function doesn't run it yet. The code inside a function only runs when you call the function, by writing its name and parentheses. If you call the function again with "Sari", the result changes too.
What if you forget to send the argument? The parameter name holds undefined, so greeting() returns Good morning, undefined!. Give the parameter a default value with =. That value is used when no argument is sent. Here morningGreeting is the same as greeting, but its parameter name has the default value "friend":
function morningGreeting(name = "friend") {
return "Good morning, " + name + "!";
}
console.log(morningGreeting()); // Good morning, friend!
console.log(morningGreeting("Budi")); // Good morning, Budi!
return: giving back a result
This function takes two numbers and gives back one multiplied by the other (the star sign means multiply):
function multiply(a, b) {
return a * b;
}
const result = multiply(3, 5);
console.log(result); // 15
- When there is more than one parameter, separate them with commas. The arguments go into the parameters in the same order:
aholds 3,bholds 5. return a * b;gives back 15. The code that called the function can store that result in a variable (const result = ...) or print it right away.returnalso stops the function. Lines inside the function afterreturndon't run.- Use the parameters, not fixed numbers.
return 3 * 5;is only right when the arguments happen to be 3 and 5.
What if a function has no return at all? Its result is undefined. Be careful: console.log inside a function only prints to the console, it doesn't give anything back. In the exercises, what gets graded is the returned value, so always use return.
Other ways to write a function
function name() { ... } is the traditional way to write a function. A function can also be stored in a variable. There is also a short form, called an arrow function and written with an arrow sign (=>). This code uses both:
const greeting2 = function (name) {
return "Hello, " + name;
};
const double = (n) => n * 2;
const triple = (n) => { n * 3; };
console.log(double(4)); // 8
console.log(triple(4)); // undefined
greeting2holds a function expression: a function stored in a variable. You call it the same way:greeting2("Budi").doubleholds an arrow function. Its parameter is on the left of=>and its body is on the right. The body is one expression (code that produces a value) with no curly braces, so the result is given back without writingreturn.tripleuses{ }. As soon as there are curly braces, the result is no longer given back automatically: the body needsreturn.triplehas noreturn, so the result isundefined.
The Arrow Functions lesson covers arrow functions in more depth.
⚠️ When the function's result isn't what you expected
console.log(a + b)inside the function only prints, so the function's result is stillundefined. Writereturn a + b;.- A function's name without parentheses, like
greetingwithout("Budi"), doesn't run the function. "Hello," + namewith no space after the comma givesHello,Budi. Spaces and punctuation inside the quote marks become part of the result, so check the text character by character.
TL;DR: A function is a named block of code that you write once and can call again and again. You make a function with function name(parameter) { ... }, and it only runs when called, for example greeting("Budi"). The values you send when calling are called arguments, and they go into the parameters in order. return gives the result back to the caller and stops the function. Without return the result is undefined, and console.log can't replace return because it only prints. An arrow function is a short way to write a function: (n) => n * 2 gives back its result directly, but once you use { } it needs a return.
⚡ Write it once, call it again and again
Write:
function greeting(name) {
return "Good morning, " + name + "!";
}
console.log(greeting("Budi")); // Good morning, Budi!
console.log(greeting("Sari")); // Good morning, Sari!
Meaning: A function is a named block of code that you write once and can call again and again. function is the keyword that makes a function, greeting is its name, and name is its parameter: a name for the value that is sent in. A function only runs when it is called. greeting("Budi") sends the value "Budi" (called the argument) into the parameter name.
⚡ return gives back the result
Write:
function multiply(a, b) {
return a * b;
}
const result = multiply(3, 5); // 15
Guess first: if return a * b; becomes console.log(a * b);, what does the function give back?
undefined. console.log only prints to the console, it doesn't give anything back. A function with no return gives undefined.
Meaning: return gives the result back to the place where the function was called, then stops the function. Here a * b means 3 times 5 (the star sign means multiply), so the result is 15, stored in result. In the exercises, what gets graded is the returned value, so always use return.
⚡ Arrow functions and curly braces
Write:
const double = (n) => n * 2;
const triple = (n) => { n * 3; };
Guess first: what does triple(4) give?
undefined. Code inside { } needs return to give back a result, and triple has no return.
Meaning: An arrow function is a short way to write a function: the parameter on the left of =>, the body (the function's code) on the right. An arrow function without curly braces gives back its result directly, so double(4) gives 8.