Ways of Defining Functions In Javascript.

Ways of Defining Functions In Javascript.

Functions are a major part of any programming language, they are known to be code blocks for a given task. Unlike most languages like Java that use more Object-Oriented Programming (OOP), functional programming is more used in javascript than OOP.

However, in javascript, there are ways 3 of defining functions.

  • Function declaration or function statement
  • Function Expression
  • Arrow functions.

Function declaration

function add(a, b) {
 return a + b;
}

This is also known as a function declaration, javascript automatically hoists the function to the top and fully initializes it. It is hoisted to the top and it can be declared anywhere in the file.

Function Expression

const add = function(a, b) {
  return a + b;
}

This hoisting also works but the variable gets hosted as undefined. It is not initialized so you can't call the function before you define it. You have to define and initialize your functions before you can call them.

Arrow Functions

Also known as a fat arrow, this is an ES6 syntax used in defining functions, the function and the return keywords are omitted; which makes your code blocks shorter

add = (a, b) => { a + b};

If you're working with just one parameter in your function, you can skip the parenthesis.

add = num => 10 + num;

However, there are limitations to this approach. When using arrow functions, there is no binding with the this keyword.

You can use any of these approaches to writing your functions but your preference should solely depend on what you want and what you're trying to achieve.