DEV Community

Ayodeji Akintubi
Ayodeji Akintubi

Posted on

Different Ways of Writing JavaScript Functions

Functions are fundamental to your versatility as a JavaScript developer. They offer you flexibility, absolute control over your code, and other benefits that make it imperative for you to master the art of function declaration.

Many newbie JavaScript developers struggle to create functions because they have zero clue about the available options.

You can write JavaScript functions in three different ways which are:

1. - Function Declaration
2. - Function Expression
3. - Arrow Function

Let’s review these function types one after the other.

  1. Function Declaration

In a function declaration, you declare the function directly without assigning it to a variable.

function functionName(parameters) {

//the code to be executed goes here

}

For example:

function sum() {
….. // content

}

Consider the example below:

function sum(a,b) {

return a + b;

}

console.log (sum(5,6)); // result = 11.

Image description

2. - Function Expression

In a function expression, you assign the function to a variable name. the following example demonstrates how you declare a function expression.

const x = functionName(parameters) {

//code goes here

}

Example:

let x = function sum(a,b) {

return a + b;

}

console.log(sum(2,20));

Image description

3. - Arrow Function

The arrow function was introduced in the JavaScript ES6 version. It is an alternative way to the methods discussed above.

Arrow functions are shorter and easier to use.

Here, you replace the “function” keyword with =>.

Consider this:

sum = (a, b) => a + b;

console.log(sum(34,20)); // result = 54

Note that you can use brackets if the function will cover multiple lines. A typical example is shown below:

const bigger = (a, b) => {

if (a > b) {

return ${a} is bigger;

} else {

return ${b} is bigger;

}

}

console.log (bigger(45,90)); // result: 90 is bigger

Image description

You can choose any of the methods discussed above to create a function, although the arrow method is currently the standard method.

Top comments (0)