Functions: The bread and butter of JavaScript programming

Functions: The bread and butter of JavaScript programming:

 

Function

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;

from Tumblr https://generouspiratequeen.tumblr.com/post/637499146050338816

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s