JS Basics
JavaScript Functions
Master JavaScript functions: declarations, expressions, arrow functions, closures, and higher-order functions.
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed when "something" invokes it (calls it).
Function Declaration vs Expression
Declaration — hoisted, can be called before defined:
function name() { ... }
Expression — not hoisted, stored in variable:
const name = function() { ... }
Arrow Function — concise syntax, no own this:
const name = () => { ... }
Higher-Order Functions
Functions that take other functions as arguments or return functions. These are the foundation of functional programming in JavaScript.
Closures
A closure is a function that has access to the outer function's variables even after the outer function has returned.
Example
javascript
// Function declaration
function add(a, b) {
return a + b;
}
// Function expression
const multiply = function(a, b) {
return a * b;
};
// Arrow functions
const subtract = (a, b) => a - b;
const square = x => x * x; // single param, no parens needed
// Default parameters
const greet = (name = "World") => `Hello, ${name}!`;
console.log(greet()); // Hello, World!
console.log(greet("Alice")); // Hello, Alice!
// Rest parameters
const sum = (...nums) => nums.reduce((acc, n) => acc + n, 0);
console.log(sum(1, 2, 3, 4, 5)); // 15
// Higher-order functions
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const big = numbers.filter(n => n > 2);
// Closures
function makeCounter() {
let count = 0;
return {
increment: () => ++count,
get: () => count,
};
}
const counter = makeCounter();
counter.increment();
counter.increment();
console.log(counter.get()); // 2Try it yourself — JAVASCRIPT