JavaScript Functions
Functions in JavaScript are fundamental building blocks that allow you to encapsulate code into reusable units. They help you perform tasks, calculations, and operations, and can be invoked multiple times throughout your code. Here’s a comprehensive look at functions in JavaScript:
1. Function Declaration
A function declaration defines a named function and can be called before it appears in the code.
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet('Alice')); // 'Hello, Alice!'
2. Function Expression
A function expression defines a function as part of an expression and can be anonymous (without a name). It is not hoisted, so it must be defined before it is called.
const greet = function(name) {
return `Hello, ${name}!`;
};
console.log(greet('Bob')); // 'Hello, Bob!'
3. Arrow Functions
Arrow functions provide a shorter syntax for writing functions and do not have their own this
context. They are often used for concise function expressions.
Basic Arrow Function:
const greet = (name) => `Hello, ${name}!`; console.log(greet('Charlie')); // 'Hello, Charlie!'
Arrow Function with No Parameters:
const sayHello = () => 'Hello, World!'; console.log(sayHello()); // 'Hello, World!'
Arrow Function with Multiple Parameters:
const add = (a, b) => a + b; console.log(add(2, 3)); // 5
Arrow Function with a Block Body:
const multiply = (a, b) => { const result = a * b; return result; }; console.log(multiply(4, 5)); // 20
4. Anonymous Functions
Anonymous functions are functions without a name, often used as arguments to other functions or in function expressions.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // [2, 4, 6, 8]
5. Function Parameters and Arguments
Functions can accept parameters, which are placeholders for values that you pass in when calling the function.
function greet(name, greeting = 'Hello') {
return `${greeting}, ${name}!`;
}
console.log(greet('David')); // 'Hello, David!'
console.log(greet('Eve', 'Hi')); // 'Hi, Eve!'
6. Returning Values
Functions can return values using the return
keyword. If no return
statement is provided, the function returns undefined
.
function add(a, b) {
return a + b;
}
let sum = add(3, 4);
console.log(sum); // 7
7. IIFE (Immediately Invoked Function Expression)
An IIFE is a function that runs as soon as it is defined. It is often used to create a new scope to avoid polluting the global namespace.
(function() {
const message = 'Hello, I am an IIFE!';
console.log(message);
})(); // 'Hello, I am an IIFE!'
8. Closures
A closure is a feature where a function retains access to its lexical scope even after the function has finished executing.
function createCounter() {
let count = 0;
return function() {
count += 1;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
9. The this
Keyword
In functions, the this
keyword refers to the object that is executing the current function. In regular functions, this
depends on how the function is called. In arrow functions, this
is lexically bound to the context in which the arrow function was defined.
const obj = {
name: 'John',
greet: function() {
console.log(`Hello, ${this.name}`);
}
};
obj.greet(); // 'Hello, John'
const greet = obj.greet;
greet(); // 'Hello, undefined' (because `this` is not bound to `obj`)
Key Points:
- Hoisting: Function declarations are hoisted, meaning you can call them before they are defined. Function expressions are not hoisted.
- Scope: Functions create their own scope, which means variables defined inside a function are not accessible outside of it.
- Callback Functions: Functions can be passed as arguments to other functions and used as callbacks for asynchronous operations or event handlers.