JavaScript is a popular programming language. With the help of this, we can work on the frontend as well as the backend.


A function is a group of reusable code, which is used to perform a single specific task. In many programming languages like JavaScript, PHP, we use functions to perform a single task in many ways. 


In this post we will discuss five approaches to write JavaScript functions with syntax and examples. We will also discuss how we can use these functions efficiently and also learn about their pros and cons.


There are many ways to write functions in JavaScript. But we will discuss here most used functions.

  1. Function Declaration
  2. Function Expressions
  3. Shorthand function
  4. Constructors
  5. Arrow function


How To Write Functions In JavaScript - Complete Guide


Function Declaration

This is the most common way to define a function in JavaScript language. To declare a function, we use the  function  keyword followed by an obligatory function name, a list of parameters in brackets, and a pair of curly braces to write the function code. 


A simple example of a function declaration in JavaScript is as follows:


function nameOfFunction (param1, param2, ...){

console.log("An example of JavaScript function.")

// line of codes...

} code-box


In this above example  nameOfFunction()  defines a variable  nameOfFunction  in the current scope of execution with the identifier equal to the function name. That means that the variable  nameOfFunction  holds the function object. 


Function hoisting

This is the most important properties of the function declaration. It allow us to use the function before the declaration in the same scope.


nameOfFunction(param1, param2, ...);

function nameOfFunction (param1, param2, ...){

console.log("An example of JavaScript function.")

// line of codes...

} code-box

To execute a declared function, we'll need to invoke it. As we saw, we just need to write the name of the function followed by brackets containing the argument if necessary.



Function Expression

A function expression is closely similar to the syntax of the function declaration. In function expression, we use  var const , or  let  keyword, followed by the function name and equal sign (=), then enter the keyword  function  followed by parameters in brackets and a pair of curly braces containing the function code.  


An example of a function expression in JavaScript is as follows:


const nameOfFunction = function(param1, param2, ...){

//lines of code...

} code-box


Function expressions are very useful if we want to write methods within objects.


const methods = {

sum: function(a, b){

return a + b;

},

substract: function(a, b){

return a - b;

},

divide: function(a, b){

return a / b;

},

multiply: function(a, b){

return a * b;

}

}

methods.sum(4,8); // Result: 12

methods.substract(4,8); // Result: -4

methods.divide(4,8); // Result: 0.5

methods.multiply(4,8); // Result: 32 code-box


Pros:

  • Easy debugging.
  • When our program will encounter an error, the stack trace will contain the name of the function.



Shorthand function

Shorthand syntax has been introduced with ES2015 and is quite similar to the getter, setter syntax.


We can define the shorthand function using the function name, followed by a list of parameters in brackets and a pair of curly braces containing the function code. This function syntax is very common when working with objects.


An example of a shorthand function in JavaScript is as follows:


const object = {

items:[],

get(index){

return this.items[index];

},

set(...elements){

this.items.push(...elements)

}

}


items.add("foo", "bar");

items.get(1) // => "bar" code-box


Pros:

  • Shorter syntax is easier to read.
  • Name functions are created, contrary to function expression.



Constructors

A constructor is a function used to create objects in JavaScript. To create a constructor, we use the keyword function followed by the name of our function, followed by a pair of parenthesis where we can add parameters, followed by a pair of curly braces describing our code logic.


An example of a constructor function in JavaScript is as follows:


function shoes(size, mark){

this.size = size;

this.mark = mark;

};

let yeezy = new shoes(35, adidas);

console.log(yeezy.size); => 35

console.log(yeezy.mark); => 'adidas' code-box


One of the most important things to notice here is the usage of the  this  and  new . To create an object from a constructor function, we use the  new  keyword. The  this  keyword refers to the object when  this  object is created.


Pros:

  • It can be used to create multiple objects.
  • If we want to add a property to objects derived from our constructor, we can do it easily.



Arrow Function

Array function is one of the most used features introduced in ES6. It allows developers to create functions in a cleaner way. 


An example of an arrow function in JavaScript is as follows:


// Arrow function

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

// Simple function

let sum = function (a,b){

return a + b;

}; code-box



function person(){

this.name = "John Wick";

// Arrow function

showName = () => {

console.log(this.name);

}

}

let someone = new person(); code-box


In arrow function the  this  keyword is a little complex. In regular function,  this  keyword represents the object that is called the function. In arrow function, the  this  keyword always represents the object that defined the arrow function.


// Regular function

function greetings() {

console.log("Hello " + this);

};

greetings(); // Result: "Hello [object Window]"

// Arrow function

var greetings = () => console.log("Hello " + this);

greetings(); // Result: "Hello [object Window]" code-box


In above both functions (regular and arrow), we get same result. Here  this  keyword represents the object window, because the function is defined in object window object scope. 


Pros:

  • Reduces a lot of code and makes it more readable. 
  • The arrow function are very effective when used for callbacks.


Cons:

  • Avoid using arrow function for event handlers, object methods, prototype methods or functions that use the arguments object.



Summary

In this post, we learned how to write functions in JavaScript in many different ways. There are some other ways to write functions in JavaScript but for the sake of simplicity, we decided to stick to the most common functions. If you have any suggestion or question then tell us in comment section.

Post a Comment

Previous Post Next Post