Function
A function in JavaScript is a piece of code contained within a block with a name associated to it. These are building blocks for almost every program that one tends to write. In simple words a function is a subprogram which is capable of performing a specific task.
There are a couple of ways by which we can create a function in JavaScript and we will go through each one them.
Function declaration
To create a function using function declaration you must use the function keyword followed by a name, followed by parenthesis which can have zero to any number of parameters and then followed by a pair of curly braces which holds the code to be executed.
Note: Function declarations are hoisted.
function square(x){
return x*x;
}
Function expression
To create a function using function expression you must follow the same steps as function declaration but you assign the function to a variable with a name which is the name of the function.
Note: Function expressions are not hoisted.
const square = function(x){
return x*x;
}
Arrow functions
These were introduced in ES6. Arrow functions helps you write shorter syntax by omitting the function keyword and replacing it with an arrow (=>) symbol which is made up of an equal to and a greater than symbol.
const square = (x) => { return x*x; }
Just in case if there is only one parameter then you can even omit the parenthesis. If there is only a single expression to be returned then you can even omit the curly braces and the return keyword.
Note: There is a difference between an expression and a statement.
const square = x => x*x;
Points to take away
- Function declaration is declared as a separate statement.
- Function expression is a part of another expression or a syntax.
- Arrow functions are handy for one-liners.
Reference: Eloquent JavaScript
Top comments (0)