A function statement is also known as a function declaration. It is hoisted, so you can call it before its definition in the code.
function a() {
console.log("Function Statement or Declaration");
}
a(); // Calling the function statement
Key Points:
A function expression is created when a function is assigned to a variable. Function expressions are not hoisted, so they must be defined before use.
var b = function() {
console.log("Function Expression");
}
b(); // Calling the function expression
Key Points:
An anonymous function is a function without a name. It is often used as a value, such as in callbacks or event handlers.
var c = function() {
console.log("Anonymous Function");
}
setTimeout(c, 2000); // Calling the anonymous function after 2 seconds
Key Points:
A named function expression is a function expression with a name. The name is only accessible inside the function itself.
var d = function namedFunction() {
console.log("Named Function Expression");
}
d(); // Works
// namedFunction(); // ReferenceError: namedFunction is not defined
setTimeout(d, 3000); // Calling after 3 seconds
Key Points:
function sum(a, b) { // a, b are parameters
return a + b;
}
sum(2, 3); // 2, 3 are arguments
In JavaScript, functions are first-class citizens. This means:
function firstClassFunctionExample() {
console.log("This is a first-class function.");
}
firstClassFunctionExample();
Key Points:
Arrow functions are a concise way to write function expressions. They do not have their own this
and are best for callbacks and methods that use the surrounding context.
const arrowFunctionExample = () => {
console.log("This is an arrow function.");
};
arrowFunctionExample();
Key Points:
this
, arguments
, or super
A callback function is a function passed as an argument to another function. They are commonly used in asynchronous programming, event handling, and functional programming patterns. Example of a callback function
function callbackExample(callback) {
console.log("Executing callback function...");
callback(); // Calling the passed callback function
}
callbackExample(() => {
console.log("This is the callback function being executed.");
});
| Concept | Hoisted | Named | Can be Anonymous | Can be Value | Example Use Case | |————————–|———|——-|——————|————–|————————-| | Function Statement | Yes | Yes | No | No | Declarations | | Function Expression | No | Yes/No| Yes | Yes | Callbacks, assignments | | Anonymous Function | No | No | Yes | Yes | Callbacks, IIFE | | Named Function Expression| No | Yes | No | Yes | Recursion, debugging | | Arrow Function | No | No | Yes | Yes | Callbacks, short syntax |