Loading Please Wait...
Arrow functions allow us to write shorter function syntax. Arrow functions were introduced in ES6.
// regular function
hello = function() {
return "Hello World!";
}
// arrow function
hello = () => {
return "Hello World!";
}
It gets shorter! If the function has only one statement, and the statement returns a value, you can remove the brackets and the return keyword. This works only if the function has only one statement.
hello = () => "Hello World!";
If you have parameters, you pass them inside the parentheses. In fact, if you have only one parameter, you can skip the parentheses as well.
hello = (val) => "Hello " + val;
// or
hello = val => "Hello " + val;
The handling of this is also different in arrow functions compared to regular functions. In short, with arrow functions there are no binding of this.
In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever.
With arrow functions the this keyword always represents the object that defined the arrow function.
<!DOCTYPE html>
<html>
<body>
<button id="btn">Click Me!</button>
<p id="result"></p>
<script>
let hello = "";
hello = function() {
document.getElementById("result").innerHTML += this;
}
//The window object calls the function:
window.addEventListener("load", hello);
//A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<button id="btn">Click Me!</button>
<p id="result"></p>
<script>
let hello = "";
hello = () => {
document.getElementById("result").innerHTML += this;
}
//The window object calls the function:
window.addEventListener("load", hello);
//A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);
</script>
</body>
</html>
How you feel about this blog:
Share this blog on:
If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com
Contact UsWe are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..
Copyright ©
, Lynxsia IT Solutions, All rights reserved