Functions in JavaScript can be defined using function declarations, function expressions, or arrow functions.
A function declaration defines a function using the function
keyword, followed by the function name, parameters, and the code block.
function greet(name) { console.log("Hello, " + name + "!"); } greet("Alice"); // Output: Hello, Alice!
A function expression assigns a function to a variable. The function can be anonymous or named.
const greet = function(name) { console.log("Hello, " + name + "!"); }; greet("Bob"); // Output: Hello, Bob!
Arrow functions provide a concise syntax for defining functions. They don't have their own this
context.
const greet = (name) => { console.log("Hello, " + name + "!"); }; greet("Charlie"); // Output: Hello, Charlie!
Functions can accept inputs known as parameters. When calling a function, the values passed are arguments.
function sum(a, b) { return a + b; } console.log(sum(3, 5)); // Output: 8
Functions can return values using the return
statement. Once a value is returned, the function exits.
function multiply(x, y) { return x * y; } let result = multiply(4, 6); console.log(result); // Output: 24
Functions have their own local scope. A closure allows a function to "remember" variables from its outer scope.
let globalVar = "I am global"; // Global variable function testScope() { let localVar = "I am local"; // Local variable console.log(globalVar); // Can access global variable console.log(localVar); // Can access local variable } testScope(); // console.log(localVar); // Error: localVar is not defined outside of testScope
function outer() { let outerVar = "I am from outer function"; function inner() { console.log(outerVar); // Inner function can access outerVar } return inner; } const closureFunction = outer(); // Returns the inner function closureFunction(); // Output: I am from outer function
An IIFE is a function that is executed immediately after being defined.
(function() { let secret = "I am secret"; console.log(secret); })();
Recursion occurs when a function calls itself. It is used to solve problems that can be broken down into smaller subproblems.
function factorial(n) { if (n <= 1) { return 1; } return n * factorial(n - 1); } console.log(factorial(5)); // Output: 120