A function is a named block of code you can run whenever you need it, as many times as you like. Instead of copying the same lines in many places, you write them once.
function sayHello() {
console.log("Hello!");
}
sayHello(); // → Hello!
sayHello(); // → Hello!
Two steps:
- Declare (define) the function with the
functionkeyword, a name and a body between curly braces. Nothing runs yet. - Call it by writing its name followed by parentheses:
sayHello(). Now the body runs.
Giving a function input
A function can receive values, called parameters, and send back a value with return.
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // → 5
console.log(add(10, 20)); // → 30
a and b are the parameters. The values you pass when calling (2 and 3) are called arguments.
Why functions matter
- No repetition. Fix a bug once, not in ten places.
- Names explain intent.
calculateTax(price)is easier to read than the maths written out. - Small pieces are easier to test and understand.
function formatPrice(amount) {
return "$" + amount.toFixed(2);
}
console.log(formatPrice(5)); // → $5.00
console.log(formatPrice(19.5)); // → $19.50
Functions are values
In JavaScript a function is a value like a number or a string: you can store it in a variable, pass it to another function and return it. That idea powers callbacks, event handlers and much of modern JavaScript. See Function Expressions and Callbacks.
Calling vs referring
function greet() { return "hi"; }
console.log(greet()); // → hi (calls it, gives the result)
console.log(typeof greet); // → function (just the function itself)
greet() runs the function. greet alone is the function value. Mixing these up is a common bug, especially with event listeners.
Forgetting the parentheses
button.addEventListener("click", greet()) runs greet right away and passes its result. You usually want to pass the function itself: greet.