JavaScript Functions: Declarations, Expressions, and First-Class Citizens
Function Statement/Declaration
Function statement and function declaration both are the same:
function a() {
console.log("hello a");
}
Function Expression
A function expression is when a function is assigned to a variable:
var b = function() {
console.log("b function called");
};
case 1:
function a() {
console.log("hello a");
}
var b = function() {
console.log("b function called");
};
a();
b();
output : hello a
b function called
case 2:
a();// hello a
b(); // it's throw error
function a() {
console.log("hello a");
}
var b = function() {
console.log("b function called");
};
The Main Difference: Hoisting
During hoisting:
For function statements, JavaScript allocates memory for a with the attached function body
For function expressions, b is declared as a variable initialized to undefined, then during code execution, it's assigned the function value
Anonymous Function
A function without a name is known as an anonymous function.
If we try to declare a function like this:
function() {
// code
}
We get a syntax error: "Function statement requires a function name"
We can use anonymous functions as values assigned to variables:
var c = function() {
console.log("c");
};
Named Function Expression
Example:
var b = function x() {
console.log("x called");
};
When we call b(), it works correctly. If we try to call x(), we'll get a ReferenceError: "x is not defined"
This happens because x is not created in the outer scope. It works like a local variable that's only accessible inside the function:
var b = function x() {
console.log(x); // x is accessible here
};
Difference between Parameters and Arguments
- Parameters are the names listed in the function definition:
function a(param1, param2) {
// param1 and param2 are parameters
}
- Arguments are the real values passed to the function:
a(argument1, argument2); // argument1 and argument2 are arguments
First Class Functions
When we can pass a function as an argument to another function or return a function from another function, this ability is known as first-class functions:
function a(param1) {
// code
}
function x() {
console.log("x function called");
}
a(x); // Passing function x as an argument
Note: "First-class citizens" or "first-class functions" both refer to the same concept.