Contents
Functions
Functions are fundamental building blocks in JavaScript. They encapsulate reusable code, allow you to organize logic, and facilitate modularity. JavaScript provides several ways to define and use functions, including function declarations, function expressions, arrow functions, callback functions, and higher-order functions.
Function Declaration
A function declaration defines a function with a name that can be called later in your code. It uses the function
keyword, followed by the function’s name, parameters (if any), and a block of code to execute.
Syntax:
function functionName(parameters) {
// Code to be executed
}
Example: Basic Function Declaration
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Output: "Hello, Alice!"
- Hoisting: Function declarations are hoisted, which means you can call them before they are defined in your code.
console.log(add(5, 3)); // Output: 8
function add(a, b) {
return a + b;
}
Function Expression
A function expression defines a function and assigns it to a variable. Unlike function declarations, function expressions are not hoisted.
Syntax:
const functionName = function(parameters) {
// Code to be executed
};
Example: Basic Function Expression
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(4, 5)); // Output: 20
- Anonymous Functions: Function expressions are often used to create anonymous functions, which are functions without a name.
Â
Example: Anonymous Function Expression
const sayHello = function() {
console.log("Hello!");
};
sayHello(); // Output: "Hello!"
Arrow Functions
Arrow functions provide a shorter syntax for writing functions and do not have their own this
context. They are especially useful for simple one-liner functions or when you need to maintain the context of this
.
Syntax:
const functionName = (parameters) => {
// Code to be executed
};
- Single Parameter: Parentheses around the parameter are optional if there is only one.
const square = x => x * x;
No Parameters: Use empty parentheses.
const greet = () => "Hello!";
Example: Basic Arrow Function
const add = (a, b) => a + b;
console.log(add(2, 3)); // Output: 5
Arrow Functions and this
:
Arrow functions do not have their own this
context. They inherit this
from the surrounding code, making them ideal for use in situations where you need to maintain the context of this
.
function Person() {
this.age = 0;
setInterval(() => {
this.age++; // Arrow function uses `this` from Person context
console.log(this.age);
}, 1000);
}
const person = new Person();
Callback Functions
A callback function is a function that is passed as an argument to another function and is executed after some operation has been completed. Callbacks are essential for handling asynchronous tasks like API calls, event handling, or timers.
Example: Basic Callback Function
function processUserInput(callback) {
const name = prompt("Please enter your name:");
callback(name);
}
function greet(name) {
console.log(`Hello, ${name}!`);
}
processUserInput(greet);
In this example, the greet
function is passed as a callback to processUserInput
and is executed after getting user input.
Example: Asynchronous Callback (setTimeout)
console.log("Start");
setTimeout(() => {
console.log("This is a callback function");
}, 2000);
console.log("End");
Output:
Start
End
This is a callback function
Higher-order Functions
A higher-order function is a function that can take other functions as arguments, return a function, or both. Higher-order functions are a key feature of JavaScript’s functional programming capabilities.
Example: Higher-Order Function
function repeatTask(task, times) {
for (let i = 0; i < times; i++) {
task();
}
}
function sayHello() {
console.log("Hello!");
}
repeatTask(sayHello, 3);
In this example, repeatTask
is a higher-order function that takes sayHello
as an argument and executes it multiple times.
Built-in Higher-Order Functions:
JavaScript provides several built-in higher-order functions for arrays, such as map()
, filter()
, and reduce()
.
map()
: Creates a new array by applying a function to each element in an array.
const numbers = [1, 2, 3, 4, 5];
const squares = numbers.map(num => num * num);
console.log(squares); // Output: [1, 4, 9, 16, 25]
filter()
: Creates a new array with elements that pass a test implemented by the provided function.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
reduce()
: Applies a function against an accumulator and each element in the array to reduce it to a single value.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, current) => accumulator + current, 0);
console.log(sum); // Output: 15
Summary
JavaScript provides various ways to define and use functions, making them versatile tools in programming. Function declarations and function expressions are the standard ways to define functions, while arrow functions offer a more concise syntax and a different this
context. Callback functions allow you to pass a function into another function, a common pattern for handling asynchronous tasks. Higher-order functions enhance JavaScript’s functional programming capabilities by taking functions as arguments or returning them. Understanding these function types is essential for building complex, efficient, and modular JavaScript applications.