Functions — All Forms
A function is a reusable named block of code that performs a specific task. It can accept inputs (parameters), execute logic, and return an output value.
Functions are the primary tool for avoiding code repetition (DRY principle) and creating abstraction. They allow you to name a process and call it anytime.
Whenever you have logic you use more than once, or logic complex enough to deserve a name. In React, every component is a function.
Define once with function keyword or arrow syntax, call many times. Parameters go in (), body in {}, return sends a value back to the caller.
📚Key Terms
Parameter— Variable in function definition: function greet(name) — name is a parameter
Argument— Actual value passed when calling: greet('Ali') — 'Ali' is the argument
Return value— The value a function sends back with the return keyword
Pure function— Always returns same output for same input, no side effects — predictable and testable
Callback— A function passed as an argument to another function, to be called later
Higher-order function— A function that takes another function as argument or returns one (map, filter, reduce)
Code Examples
#14 ways to write a function
// 1. FUNCTION DECLARATION — hoisted, can call before definitionfunction greet(name) {return "Hello, " + name;}console.log(greet("Ali")); // "Hello, Ali"// 2. FUNCTION EXPRESSION — NOT hoisted, stored in variableconst greetExpr = function(name) {return "Hello, " + name;};// 3. ARROW FUNCTION — modern, concise, no own "this"const greetArrow = (name) => {return "Hello, " + name;};// 4. ARROW — short form (single expression = implicit return)const greetShort = (name) => "Hello, " + name;// One parameter — parens optionalconst double = n => n * 2;console.log(double(5)); // 10// No parameters — parens requiredconst sayHi = () => "Hi!";
#2Default params, rest, spread, callbacks
// Default parametersfunction greet(name = "World", greeting = "Hello") {return `${greeting}, ${name}!`;}greet(); // "Hello, World!"greet("Ali"); // "Hello, Ali!"greet("Ali", "Hey") // "Hey, Ali!"// Rest parameters — collect remaining args into arrayfunction sum(...numbers) {return numbers.reduce((total, n) => total + n, 0);}sum(1, 2, 3, 4); // 10// Spread — expand array into argumentsconst nums = [3, 1, 4, 1, 5, 9];Math.max(...nums); // 9 (same as Math.max(3, 1, 4, 1, 5, 9))// Callback — function passed to another function[1, 2, 3].forEach(function(num) {console.log(num);});// Arrow callback (most common form)[1, 2, 3].map(num => num * 2); // [2, 4, 6]// Higher-order function — returns a functionconst makeAdder = (x) => (y) => x + y;const add5 = makeAdder(5);add5(3); // 8add5(10); // 15
Practice This Concept
Open the playground, paste any example, and experiment. The best way to learn is by breaking things.
Open in Playground