Arrow functions in JavaScript. Code examples open

Arrow functions in JavaScript. Code examples

Arrow functions help to reduce the allocation of common functions. The structure of the arrow function looks like this:

    (parameters) => action_functions

For example, let’s convert a normal function into a arrow function:

    function hello() {
        console.log("Hello World");
    }
    hello();

This same function is written in the form of an arrow:

    let hello = () => console.log("Hello");
    hello();

In (), we indicate the parameters of the function (in the example there are no parameters) after the symbol => we write the body of the function.

If the arrow function has only 1 parameter, then the parentheses can be omitted at all:

    let display = text => console.log(text);

    display("Text1");

To return the value from the arrow function, we just need to specify it after the => symbol:

    let sum = (x, y) => x + y;

    console.log(sum(1, 2));     // 3

Objects in arrow functions

The Object is assigned to arrow functions with the help of curly brackets.

Consider an example:

    let user = (userName, userAge) => ({ name: userName, age: userAge });

    let tom = user("Alex", 20);
    let bob = user("Antony", 21);

    console.log(tom.name, tom.age);     // "Alex", 20
    console.log(bob.name, bob.age);     // "Antony", 21

If the arrow function has a large body (several instructions), then the body of the instruction is wrapped in curly braces as in normal functions:

    const square = n => {
        let result = n * n;
        return result;
    }

    console.log(square(5));   

Where to use arrow functions

Arrow functions in JavaScript provide syntactic sugar for creating functions in a more concise and concise way. They are useful in many situations, especially when you need to pass a function as an argument or when you need to preserve the function’s execution context.

Examples:

const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map((number) => number * 2);
console.log(doubledNumbers); // [2, 4, 6, 8, 10]

In this example, we use the arrow function in the map method to double each number in the numbers array.

const button = document.querySelector('button');
button.addEventListener('click', () => {
  console.log('Pressed!');
});

Here we are using the arrow function as the click event handler for the button.

const obj = {
  numbers: [1, 2, 3, 4, 5],
  doubleNumbers() {
    return this.numbers.map((number) => number * 2);
  }
};
console.log(obj.doubleNumbers()); // [2, 4, 6, 8, 10]

In this example, we use the arrow function in the doubleNumbers method of obj to double the numbers in the numbers array.

0

More

Leave a Reply

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

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation