How to use ES6 Arrow functions with React Native

The arrow function is the most popular java script feature introduced in ES6.

What is arrow function in javascript ?

The arrow function is also called the fat arrow function introduced with ES6 as a new syntax for writing JavaScript functions.

These are few advantages of arrow function of javascript, here is the following.

  1. You don’t need to bind the function using the bind method.
  2. By using an arrow function, you don’t need to write the function keyword and return keyword (it’s implicit in arrow functions)

Here are some basic syntax with multiple parameters are as given below

const result = (x, y) => { return x + y };

With no parameter

const result = () => { alert.log(‘This is the message’); };

With one parameter

If you have one (and just one) parameter, you could omit the parentheses completely.

const result = x => { return x*x };

So here, now you can see that if the function body contains just a single statement, then
you can omit the brackets and write all on a single line:

With more than one parameters

Parameters are passed in the parentheses like below
const myFunction = () => doSomething()

const myFunction = (param1, param2) => doSomething(param1, param2)

Let’s us learn with an example

Take the below array for this example
const laptops = [
{name:’Dell inspiron series’, price: 25000},
{name:’Lenovo’, price: 35000},
{name:’Asus’, price: 17000}
]

Get all the price from the array of objects

const laptopLists = laptops.map(laptop => laptop.price);
Result:
console.log(laptopLists); // [25000, 35000, 17000]

Use of arrow function for the array filter method.

You can filter the values from the array by performing any logic to filter the items.
i.e. Need the even numbers out of the array numbers.

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const evenNumbers = array.filter(even => even % 2 === 0);
console.log(evenNumbers); // [2,4,6,8,10.12,14]

For more, visit the official documentation here

Thank you for reading!

Has this article helped you? Please share it via social media channels.

Have questions or any suggestions for improvement? Post them below.

Renish

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top