Js Functions in JavaScript
? JavaScript Functions
Functions are reusable blocks of code designed to perform a task.
1. Function Declaration
function greet(name) { return `Hello, ${name}!`;}console.log(greet("Alice")); // Hello, Alice!2. Function Expression
const greet = function(name) { return `Hello, ${name}!`;};console.log(greet("Bob"));3. Arrow Functions (ES6+)
const greet = (name) => `Hello, ${name}!`;console.log(greet("Carol"));4. Parameters and Arguments
function add(a, b = 0) { return a + b;}console.log(add(5)); // 5 (b defaults to 0)console.log(add(5, 3)); // 85. Returning Values
function square(x) { return x * x;}6. Anonymous Functions
Functions without names, often used as callbacks:
setTimeout(function() { console.log("Hello after 1 second");}, 1000);7. Immediately Invoked Function Expression (IIFE)
(function() { console.log("This runs immediately!");})();8. Rest Parameters and Default Parameters
function sum(...numbers) { return numbers.reduce((a, b) => a + b, 0);}console.log(sum(1, 2, 3, 4)); // 10Want examples of closures, callback functions, or function scopes?