β 1. What is a Function?
A function is a reusable block of code that performs a specific task.
jsCopyEditfunction greet() {
console.log("Hello!");
}
greet(); // Output: Hello!
π 2. Function Declaration
jsCopyEditfunction add(a, b) {
return a + b;
}
let result = add(2, 3);
console.log(result); // 5
π 3. Function Expression
jsCopyEditconst multiply = function(x, y) {
return x * y;
};
console.log(multiply(4, 5)); // 20
π 4. Arrow Functions (ES6)
A shorter syntax for writing functions.
jsCopyEditconst subtract = (a, b) => a - b;
console.log(subtract(10, 4)); // 6
- If only one parameter: parentheses are optional.
jsCopyEditconst square = x => x * x;
- With no parameters: use empty
()
jsCopyEditconst sayHi = () => console.log("Hi!");
π 5. Default Parameters
jsCopyEditfunction greet(name = "Guest") {
console.log(`Hello, ${name}`);
}
greet(); // Hello, Guest
greet("Alice"); // Hello, Alice
π 6. Rest Parameters (...args
)
Allows functions to accept any number of arguments.
jsCopyEditfunction sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
π 7. Callback Functions
A function passed as an argument to another function.
jsCopyEditfunction greetUser(name, callback) {
console.log("Hi " + name);
callback();
}
function sayBye() {
console.log("Bye!");
}
greetUser("Tom", sayBye);
// Output:
// Hi Tom
// Bye!
π 8. Anonymous Functions
Functions without a name. Commonly used in callbacks.
jsCopyEditsetTimeout(function() {
console.log("Delayed message");
}, 2000);
π 9. Immediately Invoked Function Expression (IIFE)
Runs as soon as it’s defined.
jsCopyEdit(function() {
console.log("This runs immediately!");
})();
π 10. Function Scope and Closure
Each function creates a new scope. Inner functions can access outer variables β this is called a closure.
jsCopyEditfunction outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
const counter = outer();
counter(); // 1
counter(); // 2
π 11. Higher-Order Functions
Functions that take another function as an argument or return a function.
jsCopyEditfunction applyOperation(x, y, operation) {
return operation(x, y);
}
function multiply(a, b) {
return a * b;
}
console.log(applyOperation(3, 4, multiply)); // 12
π§ͺ Practice Challenges
- Create a function
isEven(n)
that returnstrue
ifn
is even. - Write an arrow function
greetUser(name)
that returns"Hello, <name>!"
- Build a function
max(...nums)
that returns the largest number using rest parameters.
π Summary Table
Type | Syntax Example |
---|---|
Named Function | function sayHi() {} |
Function Expression | const add = function(a, b) {} |
Arrow Function | const square = x => x * x |
IIFE | (function() { ... })(); |
Callback | array.map(callback) |
Closure | function outer() { return function inner() {} } |
π₯ Want This as a Download?
Would you like:
- β A downloadable PDF of this tutorial?
- π» A CodePen/JSFiddle link to experiment with?
- π§ A short quiz or flashcards?