Functions
Function declaration function
A named piece of code you can run again and again with different data.
Why it exists
Without functions you'd copy the same logic everywhere it's needed: the discounted price in the cart, on the product page, in the confirmation email. And when you found a bug, you'd fix it in every copy. A function gives a piece of code a name: write it once, call it as often as you like, and a fix in one place repairs every call. Functions also split a big program into clear parts: validateForm, sendOrder, showError read like a plan.
Where it's used
- Calculations needed in several places: discounted price, tax, shipping.
- Event handlers: what to do when a button is clicked or a form is submitted.
- Checks:
isValidEmail(text),isAdult(user)— a clear name instead of a three-line condition. - Every challenge on Tasky is a function that the tests call with different arguments.
Syntax
function name(param1, param2) {
// function body
}Examples
function greet(name) {
return "Hello, " + name;
}
greet("Ann"); // → "Hello, Ann"function priceWithDiscount(price, percent) {
return price - (price * percent) / 100;
}
priceWithDiscount(2000, 10); // → 1800
priceWithDiscount(500, 50); // → 250function greet(name) {
return "Hello, " + name;
}
greet(); // → "Hello, undefined"undefinedfunction greet(name = "guest") {
return "Hello, " + name;
}
greet(); // → "Hello, guest"
greet("Bob"); // → "Hello, Bob"Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
A declaration function name(parameters) { … } only describes the function — the code inside doesn't run yet. It runs when you call it: name(arguments). At that moment the parameters get the arguments' values in order: in greet("Ann") the parameter name becomes "Ann".
Variables declared inside a function exist only during the call and aren't visible outside — every call gets its own. That's why functions don't get in each other's way.
function declarations are hoisted: JavaScript finds them before running the code, so you can call such a function even above the line where it's written.
Traps
How it differs from…
When to pick something else
If code is used once and is one or two lines long, a separate function can just make things harder to follow — the reader has to jump to its declaration. Move into a function what repeats or deserves a clear name.