What are JavaScript Arrow Functions?
Basically, ES6 provides a new way to create functions using the => operator. Thus, when you see this => operator, which obviously looks like an arrow, that’s why it is called “arrow functions”. This new method or way of creating a method gives you the ability to have a shorter syntax, and the arrow functions are anonymous functions. Lastly, if you are familiar with lambda expressions you can easily grasp this idea.
Arrow Function Syntax
I have a good idea, let’s first make a traditional function in JavaScript and then let’s try to convert it into an arrow function. Sounds like a good idea to you? Ok, let’s get started then.
Now, consider the example below.
- var getProductOfTwoNumbers = function (num1, num2){
- return num1 * num2;
- }
- const getProductOfTwoNumbers = (num1, num2) => {
- return num1 * num2;
- };
- let result = getProductOfTwoNumbers(2,2);
- console.log(result); // output equals 4
- const getProductOfTwoNumbers = (num1,num2)=> num1 * num2;
- let result = getProductOfTwoNumbers(2,2);
- console.log(result); // output equals 4
Just remember that when {} brackets are not used then the value of the statement in the body is automatically returned.
If an arrow function only contains a single argument, we can ignore the parenthesis around. See the examples below.
- //regular JavaScript function having a single argument
- var getFirstElement = function(myArrayList){
- return myArrayList[0];
- }
- //let's convert this into arrow function
- const getFirstElement = (myArrayList) => myArrayList[0];
- let result = getFirstElement([1,2,3]); //output equals 1
- //let's remove the parenthesis from (myArrayListray) to myArrayList
- const getFirstElement = myArrayList => myArrayList[0];
- let result = getFirstElement([1,2,3]); //output equals 1

Join the conversation! Your thoughts help the community grow.