Functions
Programming Languages · JavaScript Functions & Arrays · 14 min
Wrap code in reusable functions that take inputs and give back results.
Your first function
A function is a named, reusable chunk of code. You write it once, then call it by name with () whenever you need it.
function cheer() {
console.log("Hooray!");
}
cheer(); // Hooray!
cheer(); // Hooray!
The code inside doesn't run until you call it.
Write a function
sayHellothat printsHello!.Call
sayHellotwice.
Parameters: giving a function input
A parameter is a variable in the brackets. When you call the function, the value you pass in fills it.
function shout(word) {
console.log(word + "!!!");
}
shout("wow"); // wow!!!
Write
greet(name)that printsHello,then the name and!.Call
greet("Ada")andgreet("Linus").
return: getting a result back
return hands a value back to whoever called the function. Then you can print it, store it, or use it in maths.
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5
Printing shows a value; returning gives it back so the rest of your code can use it.
Write
double(n)that returnsntimes 2.Print
double(21), thendouble(5).
Arrow functions
An arrow function is a shorter way to write a function. Store it in a const. If the body is one expression, it's returned automatically, no return needed.
const square = (x) => x * x;
console.log(square(3)); // 9
Write an arrow function
triplethat returns its input times 3.Print
triple(4), thentriple(10).
Default parameters
Give a parameter a default with =. If the caller leaves it out, the default is used.
function order(drink = "water") {
return `One ${drink}, please`;
}
console.log(order("tea")); // One tea, please
console.log(order()); // One water, please
Write
welcome(name)that returnsWelcome,+ name +!, withnamedefaulting to"stranger".Print
welcome("Sam"), thenwelcome().
Put it together: tip calculator
Build two small functions where one uses the other. Functions calling functions is how bigger programs are built.
Write
tip(bill, percent)that returnsbill * percent / 100, withpercentdefaulting to15.Print
tip(40), thentip(40, 20).Write
total(bill)that returnsbill + tip(bill), and printtotal(100).
More in JavaScript Functions & Arrays
Previous: Conditionals · Next: Arrays