Computer Science

Javascript Arrow Functions

Javascript Arrow Functions are a shorthand way of writing functions in Javascript. They are anonymous functions that can be written in a more concise way than traditional functions. Arrow functions have a simpler syntax and can be used to write more readable and maintainable code.

Written by Perlego with AI-assistance

6 Key excerpts on "Javascript Arrow Functions"

  • Book cover image for: JavaScript
    eBook - ePub

    JavaScript

    The New Toys

    • T. J. Crowder(Author)
    • 2020(Publication Date)
    • Wrox
      (Publisher)
    7 .

    ARROW FUNCTIONS AND LEXICAL THIS, SUPER, ETC.

    ES2015 added arrow functions to JavaScript. Arrow functions solve a whole class of problems, particularly with callbacks: making sure that this inside the function is the same as this outside it. They're also lighter-weight and more concise than traditional functions created using the function keyword (sometimes much more concise).
    Let's start with the syntax and then we'll look more closely at this and the other things arrow functions handle differently from traditional functions.

    Arrow Function Syntax

    Arrow functions come in two forms: ones with a concise body (often called concise arrow functions) and ones with a standard function body (I call them verbose arrow functions, though they're still not as verbose as traditional functions). We'll look at the concise form first.
    Suppose you want to filter an array, keeping only the entries whose value is less than 30. You'd probably do it by using Array.prototype.filter and passing in a callback function. In ES5, that would look like this:
    var array = [42, 67, 3, 23, 14]; var filtered = array.filter(function(entry) { return entry < 30; }); console.log(filtered); // [3, 23, 14]
    This is a common use case for callbacks: a callback that needs to do something simple and return a value. Arrow functions provide a very concise way to do it:
    const array = [42, 67, 3, 23, 14];
    const filtered = array.filter(entry => entry < 30 );
    console.log(filtered); // [3, 23, 14]
    When you compare it to the traditional function you're used to, it almost doesn't look like a function at all! Don't worry, you'll soon get used to it.
    As you can see, the concise form of an arrow function is literally just the name of the parameter(s) it accepts, then an arrow ( => ) to tell the parser this is an arrow function, and then an expression defining the value it returns. That's it. No function keyword, no curly braces to define a function body, no return
  • Book cover image for: Mastering JavaScript Functional Programming
    eBook - ePub

    Mastering JavaScript Functional Programming

    Write clean, robust, and maintainable web and server code using functional JavaScript, 2nd Edition

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function for more on this, but remember that using this way of creating functions isn't a good idea!
    • Finally, the last definition, which uses an arrow => definition, is the most compact way to define a function, and the one we'll try to use whenever possible.
    At this point, we have seen several ways of defining a function, but let's now focus on arrow functions, a style we'll be favoring in our coding for this book. Passage contains an image

    Arrow functions – the modern way

    Even if the arrow functions work   pretty much in the same way as the other functions, there are some important differences between them and the usual functions. Arrow functions can implicitly return a value even with no return statement present, the value of  this is not bound, and there is no arguments object. Let's go over these three points.
    There are some extra differences: arrow functions cannot be used as constructors, they do not have a prototype property, and they cannot be used as generators because they don't allow the yield keyword. For more details on these points, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_binding_of_this .
    In this section, we'll go into several JavaScript function-related topics, including:
    • How to return different values
    • How to handle problems with the value of this
    • How to work with varying numbers of arguments
    • An important concept, currying , for which we'll find many usages in the rest of the book
    Passage contains an image

    Returning values

    In the lambda coding style, functions only consist of a result. For the sake of brevity, the new arrow functions provide a syntax for this. When you write something like (x,y,z) => followed by an expression, a return is implied. For instance, the following two functions actually do the same as the sum3() function that we showed previously:
  • Book cover image for: Web Developer's Reference Guide
    • Joshua Johanan, Talha Khan, Ricardo Zea(Authors)
    • 2016(Publication Date)
    • Packt Publishing
      (Publisher)

    ECMAScript 6 features

    ECMAScript 6, otherwise called ECMAScript 2015 , is the most recent form of the ECMAScript standard. ES6 is an important upgrade to the language, and the first update to language since the release of ES5.1 in June 2011
    A few of the new features of ES6 are:
    • Arrow functions
    • Classes
    • Enhanced object literals
    • Destructuring assignment
    • Extended parameter handling
    • Generator
    • Modules
    • Proxy
    We will look at all these functions in the upcoming sections.

    Arrow functions

    Arrow functions are also known as fat arrow functions . It is a function and is similar to what we use in C#, Java, and Coffee Script. Statements and expression bodies are supported by arrows. The lexical of arrows is similar to its surrounding code. This is not the case in functions.
    As the name suggests, arrow functions use a shorter syntax, an arrow (=> ), for definition and in syntax.
    For example, look at the following example:
    // An empty arrow function returns undefined let empty =()=>{}; (()=>"pine")()// returns "pine" var simple = a => a >20?20: a; simple(20);// 20 simple(10);// 10 let max =(a, b)=> a > b ?a : b; // Easy array filtering, mapping, ... varsampleArray=[7,4,1,0,3,5,11]; var sum =sampleArray.reduce((a, b)=> a + b);// The answer is 29 var even =sampleArray.filter(v => v %2==0);// The answer is [4, 0] var odd =sampleArray.filter(v => v %2!=0);// The answer is [7, 1, 3, 5, 11] var double =sampleArray.map(v => v *2);// The answer is[14, 8, 2, 0, 6, 10, 22]
    An arrow function expression or a fat arrow function are shorter in syntax when compared with function expressions. Arrow function is used to bind the value of this. (It does not binds its own arguments , super , this or new.target
  • Book cover image for: JavaScript for Sound Artists
    eBook - ePub

    JavaScript for Sound Artists

    Learn to Code with the Web Audio API

    • William Turner, Steve Leonard(Authors)
    • 2022(Publication Date)
    • CRC Press
      (Publisher)
    To convert a conventional callback to an arrow function you remove the function keyword and place an arrow operator to the right of the parenthesis. An arrow operator looks like the following example.
    => A conventional callback function looks like this: function(){} The arrow function version is rewritten to look like this: ()=>{} Arrow syntax can be made more concise if the callback only has a single argument. In such a case the parenthesis can be removed. let freqs = [100, 200, 300]; let newFreqs = freqs.map(val => { // argument parenthesis removed return val + 100; }); If the callback function is only used to return a value and does not contain code in the body, the return statement and curly braces can be removed as well. let freqs = [100, 200, 300]; let newFreqs = freqs.map(val => val + 100); // argument parenthesis, return statement and curly braces removed. Arrow functions are commonly used as a replacement for function expressions. An example of a function expression converted to an arrow function is demonstrated below.
    // Conventional function expression syntax let add = function (valOne,valTwo){ let result = valOne + valTwo; return result } console.log(add(2,3)) // 5 // Arrow syntax version let add = (valOne,valTwo) => { let result = valOne + valTwo; return result } console.log(add(2,3)) // 5
    Typically, if a function expression does not contain a body of code and is only used to return a value, it is written like the following example. let add = (valOne,valTwo) => valOne + valTwo; console.log(add(2,3)); // 5

    Recursion

    Recursion is an advanced programming topic, and it will only be explored briefly in this chapter. A recursive function is a function that calls itself. The following is an example of a recursive function. function x(){ return x() }
    If you run the previous code, it will crash your browser. This is because, when a recursive function runs indefinitely, it eventually uses up the resources of your code interpreter (in this case the web browser) and creates an error. To use recursion effectively, you need to set a condition to terminate the recursion. This condition is called the base case
  • Book cover image for: Full-Stack React, TypeScript, and Node
    eBook - ePub

    Full-Stack React, TypeScript, and Node

    Build cloud-ready web applications using React 17 with Hooks and GraphQL

    this context and arrow functions.

    Learning about arrow functions

    Arrow functions were a new addition to ES6. Basically, they serve two main purposes:
    • They shorten the syntax for writing functions.
    • They also automatically make the immediate scope parent, the this object, the arrow function's parent. 
    Let me explain this a bit more before continuing as it's critical knowledge for JavaScript developers. 
    In JavaScript, the this object, the owner object instance that member properties and methods belong to, can change based on the context of a call. So, when a function is called directly—for example, MyFunction() —the parent this would be the caller of the function; that is to say, the current scope's this object. For browsers, that would usually be the window object. However, in JavaScript, functions can also be used as object constructors—for example, new MyFunction() . In this case, the this object inside the function would be the object instance that was created from the new MyFunction constructor. 
    Let's look at an example to clarify as this is a really important feature of JavaScript. Create a new file called testThis.ts and add the following code:
    function MyFunction () {     console.log(this); }   MyFunction(); let test = new MyFunction(); If you compile and then run this code, you will see the following result:
    Figure 3.1 – testThis result
    So, when MyFunction is called directly, the immediate scope parent is going to be Node's global object, since we are not running in a browser. Next, if we create a new object from MyFunction using new MyFunction() , the this object becomes its own object instance since the function was used to create an object as opposed to being run directly.
    Now that we have that out of the way, let's see what an arrow function looks like. Create the arrowFunction.ts
  • Book cover image for: Learn ECMAScript
    No longer available |Learn more
    • Narayan Prusty, MEHUL MOHAN(Authors)
    • 2018(Publication Date)
    • Packt Publishing
      (Publisher)
    arrow function  is, at first glance, just a fancy way to create regular JavaScript functions (however, there are some surprises). Using arrow functions, you can create concise one-liner functions that actually work!
    The following example demonstrates how to create an arrow function:
    let circumference = (pi, r) => { let ans = 2 * pi * r; return ans;}let result = circumference(3.141592, 3);console.log(result); // Outputs 18.849552 Here, circumference is a variable, referencing to the anonymous arrow function. The previous code is similar to the following code in ES5: var circumference = function(pi, r) { var area = 2 * pi * r; return area;}var result = circumference(3.141592, 3);console.log(result); //Output 18.849552
    If your function contains just a single statement (and you want to return the result of that statement), then you don't have to use the {} brackets to wrap the code. This makes it a one-liner. The following example demonstrates this :
    let circumference = (pi, r) => 2 * pi * r;let result = circumference(3.141592, 3);console.log(result); //Output 18.849552 When {} brackets are not used then the value of the statement in the body is automatically returned. The preceding code is equivalent to the following: let circumference = function(pi, r) { return 2 * pi * r; }let result = circumference(3.14, 3);console.log(result); //Output 18.84 Also, if there's only a single argument, you can omit the brackets to make the code even shorter. Consider the following example: let areaOfSquare = side => side * side;let result = areaOfSquare(10);console.log(result); //Output 100 Since there is only one argument, side, we can omit the circular brackets for this. Passage contains an image

    The value of "this" in an arrow function

    In arrow functions, the value of the this keyword is the same as the value of the this keyword of the enclosing scope (the global or function scope, whichever the arrow function is defined inside). That means, instead of referring to the context object (that is, the object inside which the function is a property), which is the value of this in traditional functions, this instead refers to global or function scope, in which the function is called. Consider this example to understand the difference between the traditional functions and the arrow functions, this value:
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.