in

Arrow functions and regular functions in JavaScript

laptop with javascript code on the screen

[ad_1]

JavaScript, like almost all modern programming languages, provides a way to create functions that enable code reuse. For those unfamiliar with the language, there are two ways to declare functions in JavaScript.


originally, function Keywords were used and then the arrow syntax was created. Both the function keyword and the arrow syntax yield similar results, although the accessibility of the scopes is different.

Failure to distinguish between the two can cause problems and lead to incorrect usage. Latest her JS developers need to understand how each function declaration affects scope and visibility.


What are JavaScript arrow functions?

Arrow functions in JavaScript are another way to define functions that don’t use defaults. function keyword:

 function logMessage(message) {
    console.log(message);
}

const logMessage = (message) => {
    console.log(message);
}

const logMessage = message => console.log(message);

Above you can see that the same message is written in three different ways. The first uses the normal function declaration method. The following two show two ways to use ES6 arrow functions.

JavaScript first adopted arrow function syntax with the release of the ECMAScript 2015 standard. Arrow functions provided a clean and concise way to create functions quickly and an interesting solution to the long standing scoping problem within JavaScript.

With these features, arrow functions quickly became a hit with many developers. Programmers looking at modern JavaScript codebases are likely to find arrow functions as well as regular functions.

How are arrow functions different from regular functions in JavaScript?

At first glance, arrow functions don’t look much different from functions declared using the function keyword. Outside the syntax, both encapsulate a set of reusable actions that can be called from different places in your code.

Although there are similarities between the two, there are some differences that developers should be aware of.

range difference

When a normal function is declared in JavaScript, it acts as a closure creating its own scope.This can cause problems when using certain special features like setTimeout and setInterval.

Prior to ES6, there were many workarounds to raise items to a higher level scope for use in callbacks. These hacks worked, but were often difficult to understand and could lead to issues with certain variables being overwritten.

Arrow functions solved both problems in a simple and elegant way. Using an arrow function as part of a callback gives it access to the same scope as the calling function.

This allowed the function to be used as a callback without losing access to the context in which the original event was called. As a quick test to demonstrate this principle in action, you can set up a deferred messaging feature like this:

 function delayedMessage(message, delay) {

    setTimeout(function(message) {
        console.log(message);
    }, delay);

}

delayedMessage("Hello World", 1000);

The function is simple, accept message and delay in milliseconds. After the delay elapses, a message is logged to the console. However, when I run the code I get undefined It will be logged to the console instead of the passed message.

Once the callback function is executed, the scope has changed and the original message is no longer accessible. To use the message from within the closure, you need to hoist it into a global variable. This may overwrite the message before the callback.

Arrow functions are a good fix for this problem.If you replace the first argument of setTimeoutthe scope can be maintained and the function can access the passed message delayed message.

 function delayedMessage(message, delay) {

    setTimeout(() => {
        console.log(message);
    }, delay);

}

delayedMessage("Hello World", 1000);

Now, when I run delayed message The function logs a message. Additionally, this allows multiple messages to be enqueued with different delays and they all occur at the correct time.

This is due to the fact that every time. delayed message is used, it generates its own scope with its own copy of the inner arrow function.

code readability

Arrow functions are useful as callbacks, but they are also used to keep your code clean and concise. In the above section, using arrow functions, delayed message function is called.

As functions get more complex, a little clarity makes the code much more readable. When constructing an object, this simplifies the code when adding short functions.

 class counter {
    _count = 0;
    increment = () => {
        this._count += 1;
    }
    decrement = () => {
        this._count -= 1;
    }
    count = () => {
        return this._count;
    }
}

let ct = new counter();

Role in object-oriented programming

Arrow functions in JavaScript are an integral part of functional programming, but they are also used in object-oriented programming. Arrow functions can be used within class declarations.

 class orderLineItem {
    _LineItemID = 0;
    _Product = {};
    _Qty = 1;

    constructor(product) {
        this._LineItemID = crypto.randomUUID();
        this._Product = product
    }

    changeLineItemQuantity = (newQty) => {
        this._Qty = newQty;
    }
}

Declaring a method inside a class declaration with an arrow function does not change the behavior of the function inside the class. But outside the class, we expose the function so that it can be used by other classes.

Regular functions are not accessible outside the class declaration unless they are called. That is, other class declarations can inherit these functions, but cannot access them directly to create other classes.

When should I use JavaScript arrow functions?

Arrow functions in JavaScript are a very powerful feature, giving developers more control over the scopes a function can access. Knowing when a callback needs or does not need access to its parent’s scope helps developers decide which type of declaration to use.

Arrow functions give programmers a clear and concise way to write callbacks without exposing parts of the scope that need to be hidden. It also allows you to create clean and simple compositions, making functional programming in JavaScript even more possible.

JS developers should be aware of the difference between the two syntaxes and be aware of which syntax is appropriate when declaring functions.

[ad_2]

Source link

What do you think?

Leave a Reply

GIPHY App Key not set. Please check settings

    6414413c5f4f5400191a0a33

    North Korea ICBM Could Hit US Within 33 Minutes, Study Says

    1679062672 sGDMgLqhL4Lo5zkr6gobjL 1200 80

    Microsoft has made it easier to patch this Bitlocker bypass flaw in Windows