Functions: Declaration, Expression, and Arrow
11 min read
Defining Functions
Functions are reusable blocks of code. JavaScript has three main ways to write them: function declarations, function expressions, and arrow functions.
javascript
// Function declaration — hoisted to the top of its scope
function greet(name) {
return "Hello, " + name + "!";
}
// Function expression — NOT hoisted
const double = function(n) {
return n * 2;
};
// Arrow function — concise, no own `this`
const square = (n) => n * n;
const add = (a, b) => a + b;
// Arrow with a block body needs explicit return
const clamp = (n, min, max) => {
if (n < min) return min;
if (n > max) return max;
return n;
};Parameters, Defaults, and Rest
javascript
// Default parameters
function createUser(name, role = "student") {
return { name, role };
}
createUser("Alice"); // { name: "Alice", role: "student" }
createUser("Bob", "admin"); // { name: "Bob", role: "admin" }
// Rest parameters — collects remaining args into an array
function sum(...nums) {
return nums.reduce((acc, n) => acc + n, 0);
}
sum(1, 2, 3, 4); // 10Prefer arrow functions for short callbacks and when you need to inherit this from the surrounding scope. Use regular functions when you need their own this binding (event handlers that reference this, methods, constructors).
Ready to test yourself?
Practice JavaScript— quiz & coding exercises