JS Arrow Functions for Lazy Coders

An easy function to aid the Lazy.

JS Arrow Functions for Lazy Coders

If you are an avid programmer, you certainly know there will be more than one solution to the same problem. In the same notion, JS allows us to write functions in several ways, such as :

  • Function Declarations

  • Function Expressions

  • Arrow Functions

What are Arrow Functions ?

Arrow Functions are a type of function expressions but with less boiler plate code. The usage of return, {}, () in the function is minimized in Arrow functions.

  • Arrow Functions are introduced as ES6 feature in JavaScript.
  • Arrow Functions can be used as callback functions inside Array Methods.
  • Arrow Functions as they are anonymous functions cannot be used as Constructor functions.

Square of a number using Function Expressions.

const square = function(a){
    return a*a
}
console.log(square(2))
//output : 4

Two rules to create Arrow Functions :

  1. If there is only one parameter - no need to use ()
  2. If there is only one statement - no need to use return and {} and the statement should be in one line.

Square of a number using Arrow Functions.

const square = (a) => {
    return a+b
} 
console.log(square(2))
//output : 5

//Applied two rules
const square = a => a*a
console.log(square(2))
//output : 5

So, if you are a Lazy Coder, Arrow Function is the way.