Functions are values in JavaScript — you can store them, pass them, and return them. That single idea powers callbacks, array methods and everything async.
Three ways to write one: function add(a,b){ return a+b } (declaration), const add = function(a,b){...} (expression), and const add = (a,b) => a+b (arrow — the modern default for short functions).
// 1. Declaration — hoisted, callable before its line
function greet(name) {
return `Hello, ${name}!`;
}
// 2. Expression — a function stored in a variable
const shout = function (name) {
return name.toUpperCase() + "!";
};
// 3. Arrow — concise; single expression returns implicitly
const add = (a, b) => a + b;
const square = n => n * n; // one param: no parens needed
const hello = () => "hi"; // no params: empty parensfunction power(base, exp = 2) { // default value
return base ** exp;
}
power(5); // 25
power(5, 3); // 125
function sum(...nums) { // rest: gather all args
return nums.reduce((t, n) => t + n, 0);
}
sum(1, 2, 3, 4); // 10function repeat(times, action) {
for (let i = 0; i < times; i++) action(i);
}
repeat(3, i => console.log(`round ${i}`));
// you use callbacks constantly with arrays:
const nums = [1, 2, 3, 4];
const doubled = nums.map(n => n * 2); // [2,4,6,8]
button.addEventListener("click", () => {
console.log("clicked!"); // and with events
});Arrows don't get their own this — they inherit it from the surrounding code. That's usually what you want in callbacks, and exactly what you don't want in object methods.
const timer = {
seconds: 0,
start() { // normal method: own this
setInterval(() => {
this.seconds++; // arrow inherits timer's this ✓
}, 1000);
}
};
const bad = {
name: "Ada",
greet: () => `Hi ${this.name}` // ✗ arrow method: this is NOT bad
};onClick(handle()) calls it immediately — pass the reference: onClick(handle)n => { n * 2 } returns undefined — braces need an explicit returnFor short callbacks and anywhere you want to keep the surrounding this — array methods, event handlers inside classes, promises. Use normal functions/method shorthand for object methods.
A function passed as an argument to be run later — the pattern behind array methods, event listeners and asynchronous code.
A function that takes or returns other functions — map, filter and addEventListener are all higher-order.
Yes — you can call a declaration before its line in the file. Expressions and arrows are not callable until their assignment runs.