Basic Function Concepts

1. Function Declarations

A function declaration is the standard way to define named functions in JavaScript. These functions are hoisted, meaning they can be called before they are defined in the code.

console.log(sum(2, 3)); // Output: 5 (hoisting works)

function sum(a, b) {
    return a + b;
}

2. Function Expressions

A function expression involves assigning a function to a variable. Unlike declarations, these functions are not hoisted, so you must define them before using them.

const greet = function(name) {
    return `Hello, ${name}`;
};
console.log(greet("Alice")); // Hello, Alice

3. Arrow Functions

Introduced in ES6, arrow functions provide a shorter syntax and lexical scoping for this. Arrow functions are especially useful for callbacks and inline functions.

const add = (a, b) => a + b;
console.log(add(2, 3)); // 5

4. Anonymous Functions

Functions without a name are called anonymous functions. They are commonly used for inline callbacks or temporary usage. It can be made using arrow functions or function expressions.

const numbers = [1, 2, 3];
numbers.forEach(function(num) {
    console.log(num * 2);
});

5. Immediately Invoked Function Expressions (IIFE)

An IIFE is a function that is executed immediately after it is defined. They are useful for creating private scopes to avoid polluting the global namespace.