Rest Parameters
Rest parameters allow a function to accept an indefinite number of arguments as an array.
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10
Hoisting
Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope.
console.log(x); // Output: undefined
var x = 5;
Immediately Invoked Function Expression (IIFE)
An IIFE is a function that runs as soon as it is defined.
(function() {
console.log('IIFE executed');
})();
Higher-Order Functions (HOFs)
Higher-order functions are functions that take other functions as arguments or return functions as their result.
function greet() {
return function(name) {
console.log('Hello, ' + name);
};
}
const greetPerson = greet();
greetPerson('Alice'); // Output: Hello, Alice
Callback Functions
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function.
function fetchData(callback) {
setTimeout(() => {
callback('Data fetched');
}, 1000);
}
fetchData((message) => {
console.log(message); // Output: Data fetched
});
First-Class Functions
In JavaScript, functions are treated as first-class citizens, meaning they can be assigned to variables, passed as arguments, and returned from other functions.
const sayHello = function() {
console.log('Hello!');
};
sayHello(); // Output: Hello!
Pure Functions
A pure function is a function that, given the same inputs, will always return the same output and does not have any side effects.
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // Output: 5
Impure Functions
An impure function is a function that may produce different outputs for the same inputs or has side effects.
let counter = 0;
function increment() {
counter++;
}
increment();
console.log(counter); // Output: 1
Global Scope
Variables declared in the global scope are accessible from anywhere in the code.
var globalVar = 'I am global';
function displayGlobalVar() {
console.log(globalVar);
}
displayGlobalVar(); // Output: I am global
Local Scope
Variables declared within a function are in the local scope and are not accessible outside that function.
function localScopeExample() {
var localVar = 'I am local';
console.log(localVar);
}
localScopeExample(); // Output: I am local
console.log(localVar); // Error: localVar is not defined
Closures
A closure is the combination of a function and the lexical environment within which that function was declared.
function outerFunction() {
let outerVariable = 'I am outside!';
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
const closureExample = outerFunction();
closureExample(); // Output: I am outside!