React Tutorials
React ES6
React Hooks
Arrow functions allow us to write short work syntax:
hello = function() {
return "Hello World!";
}
hello = () => {
return "Hello World!";
}
Be short! If the function has only one statement, and the statement returns the value, you can remove the brackets and the return
keyword:
hello = () => "Hello World!";
Note: This only works if the function has only one statement.
If you have parameters, you are moving them between parentheses:
hello = (val) => "Hello " + val;
In fact, if you only have one parameter, you can skip and circle:
hello = val => "Hello " + val;
this
?The handling of this
also differs from the arrow functions as compared to the normal functions.
In short, with arrow functions there is no obligation for this
.
In normal operations this
keyword represented something that called the function, which could be a window, a document, a button or anything.
With arrow functions, this
keyword always represents something that describes the function of an arrow.
Let's look at two examples to see the difference.
Both examples call the process twice, first when the page loads, and again when the user clicks a button.
The first example uses a standard function, and the second example uses an arrow function.
The result shows that the first example returns two different items (window and button), and the second example returns the Title item twice.
With a regular function, this
represents the object that called the function:
class Header {
constructor() {
this.color = "Red";
}
//Regular function:
changeColor = function() {
document.getElementById("demo").innerHTML += this;
}
}
const myheader = new Header();
//The window object calls the function:
window.addEventListener("load", myheader.changeColor);
//A button object calls the function:
document.getElementById("btn").addEventListener("click", myheader.changeColor);
With an arrow function, this
represents the Header object no matter who called the function:
class Header {
constructor() {
this.color = "Red";
}
//Arrow function:
changeColor = () => {
document.getElementById("demo").innerHTML += this;
}
}
const myheader = new Header();
//The window object calls the function:
window.addEventListener("load", myheader.changeColor);
//A button object calls the function:
document.getElementById("btn").addEventListener("click", myheader.changeColor);
Remember this difference when working with tasks. Sometimes normal job behavior is what you want, if not, use arrow functions.