How to use Arrow Functions in Javascript

How to use Arrow Functions in Javascript

All what you need to know about Javascript Arrow functions.

Welcome, in this article I will show you how to use Arrow function in Javascript with examples on how they work.

Let's dive in.

With the introduction of ECMAScript 2015, also known as ES6, JavaScript arrow functions were made available. The handling of the this keyword and arrow functions' succinct syntax made them a popular feature among developers very fast. We can write shorter function syntax using arrow functions:

Like this code below;

hello = function() {
  return "Hello World!";
}

The code above can be shorten by using arrow function, which will become this.

Hi = () => "Hi Michael!";

Why Use this function?

• No curly{} Bracket in the code

• It's consist of just one line of Code

• No return and function keyword

The code will still function with or without the parenthesis if the function only has one parameter, in which case we can omit the parentheses (though we can still use them in the code).

Example without parentheses

hello = val=> "Hello " + val;

But you must add an empty set of parentheses (_) before the Javascript arrow function => if the function has more than one parameter or none at all. The same is applicable if a function has multiple parameters.

Example

(Samuel,Michael,John) => Name;

You may make ES6 arrow syntax even shorter when your function body just contains one expression. You may eliminate the return keyword, get rid of the curly brackets, and keep everything on one line. The outer function will contain a parameter and return an anonymous function, thus we must be careful when employing one-liners and parenthesis-free javascript arrow functions.

Anonymous Function

Anonymous functions are those that don't have a name identifier between the function keyword and the parameter list.

An anonymous function is like this;

const anonymousArrowFunc = () => 'You can\'t identify me!'

Arrow Function as an Object Method

All arrow functions must be understood to be anonymous functions. Due to the way arrow functions use lexical scoping for this, they are ineffective as object methods. See how the code will be run by looking at the example below.

const printNumbers = {
  phrase: 'The current value is:',
  numbers: [1,2 , 3,4 ],

  loop: () => {
    this.numbers.forEach((number) => {
      console.log(this.phrase, number)
    })
  },
}

An arrow function will search outside the object for the value of this because, as we must be aware, an object does not generate a new lexical scope.

Implicit Return

The concise body is another name for this. It permits the removal of the return keyword and curly {} brackets, which are always present in a typical function that is enclosed in a block.

const sum = (1, 2) => {
  return 1 + 2
}

Now this;

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

Keep in mind that you must omit the return keyword as well as the brackets {}. You must use the standard block body syntax if the body cannot be written as a one-line return statement. The object syntax will be considered as a function body rather than a return value if it is not enclosed in parentheses.

const sum = (a, b) => ({result: a + b})

sum(3, 5)

This will give the following output:

{result: 8}

Additionally, parentheses around a single parameter in a function can be removed. Removing and not removing the parentheses around a single parameter will still work the same, but if there is no parameter in the function parentheses will be required.

const greet = () => 'Hello!'

greet()

Calling greet will give us;

"Hello!"

This Function

The object that called the function was represented by the this keyword in regular functions. This object may be a window, document, button, or anything else. The object that specified the arrow function is always represented by the this keyword when used with arrow functions.

Let's look at the examples below

// Regular Function:
hello = function() {
  document.getElementById("demo").innerHTML += this;
}

// The window object calls the function:
window.addEventListener("load", hello);

// A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);

This represents the object that calls the function when it is a normal function.

// Arrow Function:
hello = () => {
  document.getElementById("demo").innerHTML += this;
}

// The window object calls the function:
window.addEventListener("load", hello);

// A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);

Benefits of Arrow Functions

If you've worked with popular programming languages like Java, Python, C#, etc., you know that the this or self operators inside of a method relate to the object that called the method, not the method itself. Some programmers find it quite difficult to use this when writing javascript codes. Using Arrow functions has two main advantages.

One is that it has a shorter syntax, which means less code is needed. Let's look the code below function funcName(params) { return params + 2; } funcName(2); // 4 This above code indicates one of the two reasons for creating arrow functions: shorter syntax

This above code can be simplify into one line of code;

(parameters) => { statements }

And if there are no parameters, the code will become,

() => { statements }

The key advantage is that it eliminates the various pain areas connected to this operator. An arrow function does not bind this way a conventional function does. Instead, this is lexically bound (i.e. this keeps its meaning from its original context).

When Should I use Arrow Function

• Since utilizing arrow function syntax instead of standard function syntax makes the code easier to read, understand, and write more effectively, we may use it with methods connected with arrays, such as map(), reduce(), and filter().

• In contrast, by using traditional function syntax concepts like callback hells, promise chaining would eventually become more challenging to understand, or even writing would become a little complex. If we are allowed to use arrow functions when declaring promises and callbacks, then it would be much easier for any user to understand the concept behind them.

Differences between Arrow Function and Regular Functions.

  1. This Value

For Regular function;

This variable, also known as the execution context, is dynamic inside a typical JavaScript function.

The value of this is dependent on how the function is called because of the dynamic context.

For Arrow Functions;

The behavior of this inside an arrow function is very different from the behavior of this inside an ordinary function. No specific execution context is defined by the arrow function.

2 Arguments Object

For Regular Object;

Arguments, a unique object resembling an array that is contained inside the body of a standard function, contains a list of the arguments that were used to call the function.

For Arrow Functions;

On the other hand, an arrow function doesn't define a particular keyword for parameters.

The arguments object is resolved lexically once more (as with this value), and the arrow function retrieves the arguments from the outer function.

Do Arrow function has limitations?

Yes

Arrow functions limitations are listed below;

• There are no specific bindings for an arrow function using this or super.

• It is not recommended to utilize an Arrow function as a method.

• A constructor cannot utilize an arrow function.

• Within its body, an arrow function cannot use yield.

• It is Incompatible with call apply and bind methods is the arrow function.

Conclusion

In this article,I've reviewed all what you need to know on how to use Arrow Function in Javascript. Kindly let me know your view about this.