Functions are reusable blocks of logic that form the building blocks of JavaScript applications.
1. Function Declaration vs Arrow Function
⊞Code Example
// 1. Traditional Function Declaration
function calculateTotal(price, taxRate = 0.18) {
return price + (price * taxRate);
}
// 2. ES6 Arrow Function (Concise syntax)
const calculateDiscount = (price, discountPercent) => price - (price * (discountPercent / 100));
// Implicit return for single expressions
const double = (n) => n * 2;
2. Scope & Closures
⊞Code Example
function createCounter() {
let count = 0; // Private encapsulated variable
return function() {
count++;
return count;
};
}
const counterA = createCounter();
console.log(counterA()); // 1
console.log(counterA()); // 2
