What is arrow function in JavaScript with example?

Asked 19-Jul-2021
Viewed 172 times

1 Answer


0

The Anonymous Functions and Arrow Functions functions are created by implementing the Closure Class. Arrow Functions also support the same functionalities that Anonymous Functions does, the only difference is that we do not have to use the use keyword for external variables in Arrow Functions. We can access these variables directly.

Like Anonymous Functions and Normal Functions, in Arrow Functions also we can easily use Normal Variables, Variable reference, defining variable type, declare function return type, default parameter, optional parameter, variable length arguments etc.

Syntax

[variable] = ( [arguments,---] ) => { statement }

Example:

hello = () => {

  return 'Hello World!';
}
hello = () => 'Hello World!';

hello = (val) => 'Hello ' + val;
const materials = [

  'Hydrogen',
  'Helium',
  'Lithium',
  'Beryllium'
];
console.log(materials.map(material => material.length));
// Traditional Function

function (a){
  return a + 100;
}
let add = (x, y) => { return x + y; };

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrow Function</h2>
<p id='demo'></p>
<script>
var hello;
hello = () => {
  return 'This is arrow function !!!';
}
document.getElementById('demo').innerHTML = hello();
</script>
</body>
</html>

Output:

JavaScript Arrow Function

This example shows the syntax of an Arrow Function, and how to use it.
This is arrow function !!!