Converting Typescript fat arrow syntax to regular Javascript syntax

I recently started learning typescript and I'm having trouble understanding the => arrow function. Could someone clarify the meaning of this JavaScript code snippet for me:

this.dropDownFilter = values => values.filter(option => option.value !== 'Others')

Answer №1

When arrow functions are not used in a special way to handle scope, the code would look like this:

this.dropDownFilter = function(values){
  return values.filter(function(option){ return option.value !== 'Others' })
}

Answer №2

When exploring the documentation for the fat arrow syntax, you will come across various examples such as:

arg => console.log(arg); // <-- () not necessary for single argument
(a, b) => console.log(a,b); // <-- () required for multiple arguments
arg => { return arg; } // <-- includes a return statement within {}
(a, b) => { return a+b; } // <-- includes a return statement within {}

this.dropDownFilter = values => values.filter(option => option.value !== 'Others')

One key advantage is that it inherently incorporates lexical this. Therefore, there is no need to store this in a variable to utilize it within the function.


This can be likened to:

this.dropDownFilter = function(values) {
  return values.filter(function(option) {
    return option.value !== 'Others'
  })
}

If we analyze further:

  1. The assignment of an anonymous function with the argument values to this.dropDownFilter.
  2. The fat arrow syntax features an implicit return statement.
  3. The inner .filter() method contains an anonymous function responsible for returning the filtered value.

Answer №3

This code snippet illustrates the syntax for defining a function in JavaScript, where the arguments are placed to the left of =>, and the function body is on the right of =>. Two important points to note:

  1. Arguments are typically enclosed in parentheses similar to traditional function syntax, but when there's only one argument, the parentheses are optional.
  2. When an arrow function consists of just one statement (as in the provided code snippet), that statement serves as the implicit return statement. For multiple statements, the function body must be wrapped in curly braces and include an explicit return keyword.

For instance:

function myFunc (arg1) {
  return arg1
}

is the same as:

var myFunc = arg1 => arg1

and also equivalent to:

var myFunc = (arg1) => {
  return arg1
}

There are additional considerations such as the context of this (which behaves differently in arrow functions) and the lack of support for the arguments keyword in arrow functions. For further details, you can refer to MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Enhance your development experience with the TypeScript definitions for the Vue 2 plugin

Currently, I am utilizing VSCode alongside TypeScript classes for developing Vue 2 components. You can check out more information at: vuejs/vue-class-component. Within my present project, I make use of plugins like vue-i18n for handling translations of la ...

Utilizing React to pass parent state to a child component becomes more complex when the parent state is derived from external classes and is subsequently modified. In this scenario,

I'm struggling to find the right way to articulate my issue in the title because it's quite specific to my current situation. Basically, I have two external classes structured like this: class Config { public level: number = 1; //this is a s ...

What is the best way to refine the dataSource for a table (mat-table) using ngx-daterangepicker-material?

I am facing a new challenge and feeling unsure about how to approach it. The issue at hand is filtering a table based on the date range obtained through the ngx-daterangepicker-material library. This library triggers events that provide a start date and a ...

Every time I attempt to execute an npm command, such as ng new, I encounter a "module not found" error despite having installed node version "v16.13.0"

https://i.stack.imgur.com/RBxyI.png node:internal/modules/cjs/loader:936 throw err; ^ Error: Cannot locate module 'C:\Program Files\nodejs\node_modules\npm\bin\node_modules\npm\bin\npm-cli.js' ...

Dealing with time zone offsets in Angular 2 Date Pipe even without a specific offset

I am currently facing an issue with converting a date string to display it on the UI using the date pipe in Angular. Below is an example of the date value: "2017-02-07T21:23:19.163" Here is the template code I am working with: <div class="input-gro ...

NX combined with Nest.js and TypeORM, further enhanced with Webpack and Migrations

Recently, I embarked on a project using NX (Nest.js + Angular) and set up TypeORM for database configuration. While everything runs smoothly in "serve" mode, I found myself struggling with configuring migrations. In a typical Nest.js project, all files in ...

Firestore TimeStamp.fromDate is not based on UTC timing

Does anyone have a solution for persisting UTC Timestamps in Firestore? In my Angular application, when I convert today's date to a Timestamp using the code below, it stores as UTC+2 (due to summer time in Switzerland). import {firebase} from ' ...

Using Angular 8, you can create a reactive form that includes a custom ng-select component which has

My custom angular reactive form includes a ng-select component along with other elements. I have implemented the following code to validate the form: private validateCustForm() { this.validation.touchFormControls(this.appointmentForm); if (this.ap ...

Using masonry-layout with Next Js leads to a ReferenceError stating that window is not defined

Implementing the masonry-layout library by David Desandro in my Next app has been a smooth process. You can find the link here. When I apply it, the masonry layout functions perfectly as intended. Here's how I'm incorporating it successfully: imp ...

Subtracted TypeScript concept

Is it possible to create a modified type in Typescript for React components? import {Component, ComponentType} from 'react'; export function connect<S, A>(state: () => S, actions: A){ return function createConnected<P>(componen ...

In order to address the issue of displaying a 404 error in In-Memory Angular,

I have watched all the videos regarding the In-memory web API and diligently followed all the steps and instructions. However, I am still encountering a 404 Error. Please inform me if I missed something or made an error. I have attempted to troubleshoot an ...

pick only one option from each row

I am working on a feature where I have five rows with two checkboxes each generated using a loop and property binding. Currently, clicking on one checkbox selects all elements in the column. However, I want to achieve selection row-wise. Is there a method ...

Encountering a 504 Gateway Timeout error while attempting to send a POST request to an API route in a NEXT.JS application that

I encountered a 504 error gateway timeout when attempting to post a request to api/webhooks, and in the Vercel log, I received a Task timed out after 10.02 seconds message. This code represents a webhook connection between my clerk and MongoDB. [POST] [m ...

Tips for validating form input upon submission in Angular 6

Within my Angular application, I have successfully implemented form validators. However, I am aiming to trigger form validation specifically upon submission. This means that when the user clicks on the submit button and the form is invalid, the errors indi ...

React's .map is not compatible with arrays of objects

I want to retrieve all products from my API. Here is the code snippet for fetching products from the API. The following code snippet is functioning properly: const heh = () => { products.map((p) => console.log(p.id)) } The issue ari ...

The Angular HTML Autocomplete feature is not functioning as intended when hosted on a CDN in Chrome, despite setting it to "nope" or "off"

When setting Autocomplete to "nope" or "off" in my input box for surname, I'm still able to select from the autocomplete list. This issue occurs when accessing our Ui app through CDN at link [https:// Xyz. net], but works correctly when accessing it d ...

How can debugging in Chrome be achieved using Typescript?

How is it possible to debug TypeScript in Google Chrome when the browser only understands JavaScript? I find myself debugging my TypeScript files within my Angular project, which was created using Angular CLI, through the Chrome developer tools. However, ...

What are the steps for incorporating the AAD B2C functionality into an Angular2 application with TypeScript?

I recently built a web application using Angular2 and TypeScript, but now one of my clients wants to integrate Azure B2C for customer login instead of OAuth. I followed a simple example on how to implement Azure B2C in a .NET Web app through the link provi ...

Increasing the token size in the Metaplex Auction House CLI for selling items

Utilizing the Metaplex Auction House CLI (ah-cli) latest version (commit 472973f2437ecd9cd0e730254ecdbd1e8fbbd953 from May 27 12:54:11 2022) has posed a limitation where it only allows the use of --token-size 1 and does not permit the creation of auction s ...

Error in Continuous Integration for Angular 4: Unable to access property 'x' of an undefined variable

i am trying to display some data on the form but encountering an error: TypeError: Cannot read property 'title' of undefined below is my component code : book:Book; getBook(){ var id = this.route.snapshot.params['id']; ...