In this blog post we will see, what exactly is first class functions in javascript. Before understanding directly what are first class functions in javascript, let's first understand some common terms like Function Statement, Function Expression, Function Declaration, Anonymous Function, Named Function Expression, Function Arguments and Function Parameters.
So Let's Get Started
✔ Function Statement
The function statement defines or declares the function, it will not be used directly until and unless you invoked it.
Example :-
function a() {
console.log("a called");
}
a();
a called
✔ Function Expression
A function expression is stored in variables like var, const and let. The difference between a function expression and a function statement is the function name, which can be omitted in function expressions to create anonymous functions.
Example :-
var b = function () {
console.log("b called");
}
b();
b called
✔ Difference Between Function Statement And Function Expression
The difference between these two is in hoisting point of view. Let's see how,
Function Statement Example :-
a();
function a() {
console.log("a called");
}
a called
Function Expression Example :-
b();
var b = function () {
console.log("b called");
}
TypeError: b is not a function
In short, function statements are hoisted but function expressions are not hoisted.
✔ Function Declaration
Function Statement and Function Declaration are same.
✔ Anonymous Function
Function without a name is called as anonymous function, they does not have their own identity.
function () {
}
SyntaxError: Function statements require a function name
Anonymous functions are used in a place where functions are used as values i.e we can assign anonymous function to a variable.
✔ Named Function Expression
Here instead of using anonymous function, we are using function with a name.
Example :-
var b = function xyz() {
console.log("b called");
}
b();
b called
Example (Corner Case) :-
var b = function xyz() {
console.log("b called");
}
xyz();
ReferenceError: xyz is not defined
Example (Corner Case) :-
var b = function xyz(){
console.log(xyz);
}
b();
ƒ xyz() { console.log(xyz); }
✔ Function Arguments And Function Parameters
Function arguments are the real values passed to the function while function parameters are the names listed in the function definition. ✔ First Class Functions
The ability to use functions as value in variable and can be passed as an argument to another function and can be returned from functions is called as first class functions. Simply, we are using functions as values.
Example :-
var b = function(param){
return function xyz(){
};
};
console.log(b());
ƒ xyz() { }
Functions are the first-class citizens in JavaScript. We can pass functions to other functions as arguments, return them from other functions as values, and store them in variables.
Hope you liked this!