Learn JS #35

JavaScript Arrow Function

Arrow functions were introduced in ES6.

Arrow functions allow us to write shorter function syntax:

let myFunction = (a, b) => a * b;

Before:

hello = function() {
  return "Hello World!";
}

With 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:


Arrow Functions Return Value by Default:

hello = () => "Hello World!";

Note: This works only if the function has only one statement.

If you have parameters, you pass them inside the parentheses:


Arrow Function With Parameters:

hello = (val) => "Hello " + val;

In fact, if you have only one parameter, you can skip the parentheses as well:


Arrow Function Without Parentheses:

hello = val => "Hello " + val;


What About this?

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.

Let us take a look at two examples to understand the difference.

Both examples call a method twice, first when the page loads, and once again when the user clicks a button.

The first example uses a regular function, and the second example uses an arrow function.

The result shows that the first example returns two different objects (window and button), and the second example returns the window object twice, because the window object is the “owner” of the function.

Example

With a regular function this represents the object that calls the function:

// Regular Function:
hello = function() {
  document.getElementById("demo").innerHTML += this;
}

// The window object calls the function:
window.addEventListener("load", hello);

// A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);

Example

With an arrow function this represents the owner of the function:

// Arrow Function:
hello = () => {
  document.getElementById("demo").innerHTML += this;
}

// The window object calls the function:
window.addEventListener("load", hello);

// A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);

Note: Remember these differences when you are working with functions. Sometimes the behavior of regular functions is what you want, if not, use arrow functions.

Categories

235 Responses

  1. Hello bro!More info!..
    дом престарелых в Ростове-на-Дону
    https://pansionat-rnd.ru/
    “Дом престарелых” – это общепринятое название для социального учреждения, которое оказывает услуги по социальной защите и помощи престарелым людям. Если вы ищете информацию о конкретном доме престарелых в Ростове-на-Дону, можете уточнить местоположение и другую информацию.
    сеть пансионатов

  2. Long-Term Effects. Some are medicines that help people when doctors prescribe.
    stromectol 3mg
    Definitive journal of drugs and therapeutics. Top 100 Searched Drugs.

  3. Actual trends of drug. drug information and news for professionals and consumers.
    https://lisinopril.science/# zestoretic 10 12.5 mg
    Prescription Drug Information, Interactions & Side. Some are medicines that help people when doctors prescribe.

  4. Get warning information here. Some are medicines that help people when doctors prescribe.
    levaquin order
    Commonly Used Drugs Charts. Learn about the side effects, dosages, and interactions.

  5. Learn about the side effects, dosages, and interactions. Everything about medicine.
    https://mobic.store/# can i buy cheap mobic price
    Comprehensive side effect and adverse reaction information. Some are medicines that help people when doctors prescribe.

  6. Everything information about medication. Some are medicines that help people when doctors prescribe.
    zithromax tablets
    Everything information about medication. Everything about medicine.

  7. safe and effective drugs are available. Some trends of drugs.
    https://clomiphenes.com get generic clomid tablets
    п»їMedicament prescribing information. Some are medicines that help people when doctors prescribe.

  8. Prescription Drug Information, Interactions & Side. Commonly Used Drugs Charts. https://amoxicillins.com/ can you buy amoxicillin over the counter in canada
    Prescription Drug Information, Interactions & Side. Drug information.

  9. Long-Term Effects. drug information and news for professionals and consumers.
    https://canadianfast.online/# buy prescription drugs without doctor
    Best and news about drug. Comprehensive side effect and adverse reaction information.

  10. Comprehensive side effect and adverse reaction information. Get warning information here.
    canadian online drugs
    Get information now. Comprehensive side effect and adverse reaction information.

  11. Medscape Drugs & Diseases. drug information and news for professionals and consumers.
    https://canadianfast.com/# buy anti biotics without prescription
    Prescription Drug Information, Interactions & Side. Top 100 Searched Drugs.

  12. Some are medicines that help people when doctors prescribe. Prescription Drug Information, Interactions & Side.
    https://canadianfast.online/# canadian pharmacy online
    Learn about the side effects, dosages, and interactions. Drug information.

  13. Some are medicines that help people when doctors prescribe. Cautions.
    https://viagrapillsild.online/# viagra for sale online
    drug information and news for professionals and consumers. Learn about the side effects, dosages, and interactions.

Leave a Reply

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