A function is a named, reusable block of code. You give it inputs called parameters, it does some work, and it can hand back a result with return. Functions let you write a piece of logic once and use it anywhere. In JavaScript they are also ordinary values: you can store them in variables, pass them to other functions and return them, which is the basis of event handling and array methods.
In this lesson you will learn
- Function declarations, function expressions and arrow functions
- Parameters, default values and
return - Local and global scope
- Callbacks: passing a function to another function
- Closures: functions that remember their variables
Three Ways to Write a Function
// Function declaration
function area(width, height) {
return width * height;
}
// Function expression
const perimeter = function (width, height) {
return 2 * (width + height);
};
// Arrow functions
const square = (n) => n * n;
const greet = (name = "friend") => `Hello, ${name}!`;
console.log(area(4, 5), perimeter(4, 5), square(9));
console.log(greet("Karim"), greet());
function noReturn() {}
console.log(noReturn()); // undefined
Output
20 18 81
Hello, Karim! Hello, friend!
undefined
- A declaration starts with the
functionkeyword and a name. Declarations are “hoisted”, so you can call them before the line where they are written. - A function expression stores an unnamed function in a variable. It can only be used after that line.
- An arrow function (
=>) is a shorter expression. With a single expression and no braces, the result is returned automatically, as in(n) => n * n. name = "friend"is a default parameter, used when the caller passes nothing.- A function without
returngives backundefined.
Scope, Callbacks and Closures
let total = 0; // global scope
function addToTotal(amount) {
const doubled = amount * 2; // local: only exists inside the function
total += doubled;
}
addToTotal(5);
addToTotal(10);
console.log("total:", total);
// console.log(doubled); // ReferenceError: doubled is not defined
// Functions are values: pass one to another (a callback)
function repeat(times, action) {
for (let i = 1; i <= times; i++) action(i);
}
repeat(3, (i) => console.log("Step", i));
// A function that returns a function (closure)
function makeCounter() {
let count = 0;
return () => ++count;
}
const next = makeCounter();
console.log(next(), next(), next());
Output
total: 30
Step 1
Step 2
Step 3
1 2 3
- Variables declared inside a function are local:
doubleddoes not exist outsideaddToTotal(). Functions can read and change variables from outer scopes, such astotal. repeat()receives a function as itsactionparameter and calls it. A function passed like this is a callback; event listeners andmap()work the same way.makeCounter()returns an arrow function that still has access tocountaftermakeCounter()has finished. That remembered access is a closure, and it is how JavaScript keeps private state.
Declaration vs Arrow Function
function | Arrow => | |
|---|---|---|
| Can be called before its line | Yes (declarations) | No |
Own this | Yes | No, uses the surrounding this |
| Implicit return | No | Yes, without braces |
| Typical use | Named helpers, object methods | Short callbacks |
Common Mistakes
- Forgetting
return, so the function givesundefined. - Adding braces to an arrow function without
return:(n) => { n * n }returns undefined. - Calling instead of passing:
button.addEventListener("click", save())runssaveimmediately. Passsavewithout parentheses. - Returning an object literal from an arrow function without wrapping it in parentheses: write
() => ({ ok: true }).
Practice Exercises
Exercise 1. Write an arrow function toFahrenheit(c) that converts Celsius to Fahrenheit.
Show answer
const toFahrenheit = (c) => c * 9 / 5 + 32;
console.log(toFahrenheit(30)); // 86
Exercise 2. Write max3(a, b, c) that returns the largest of three numbers without using Math.max.
Show answer
function max3(a, b, c) {
let biggest = a;
if (b > biggest) biggest = b;
if (c > biggest) biggest = c;
return biggest;
}
console.log(max3(4, 11, 7)); // 11
Frequently Asked Questions
How do I accept any number of arguments?
Use a rest parameter: function sum(...nums) collects all arguments into an array called nums.
What is the difference between a parameter and an argument?
A parameter is the name in the function definition, such as width. An argument is the actual value passed when calling it, such as 4.
Summary
- Write functions as declarations, expressions or arrow functions.
- Parameters can have defaults;
returnsends a value back. - Variables inside a function are local to it.
- Functions are values: they can be callbacks and can form closures.
Next: JavaScript Arrays.
