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

When utilizing custom ngDoBootstrap and createCustomElement in Angular, the router fails to recognize the URL being used

WHEN I implement a custom ngDoBootstrap function instead of the default bootstrap: [AppComponent] like shown below: @NgModule({ imports: [ BrowserModule, FormsModule, AppRoutingModule ], declarations: [ AppComponent, HelloComponent ], exports: ...

A Typescript function will only return a partial if the parameter passed into it is also

I have a function that takes a camelCase object and returns the same object in snake_case format. // Let's consider these types interface CamelData { exempleId: number myData:string } interface SnakeData { exemple_id: number my_data: stri ...

What is the best way to compile TypeScript files without them being dependent on each other?

I have created a TypeScript class file with the following code: class SampleClass { public load(): void { console.log('loaded'); } } Now, I also have another TypeScript file which contains functions that need to utilize this class: // ...

Error message "Angular build with --prod causes Uncaught TypeError: e is not a constructor when running ng serve"

I am encountering an issue while deploying my Angular application to production. The application functions correctly in development and had previously worked on production as well. To build the application, I am using: ng build --prod --base-href="/site/ ...

Issues with utilizing destructuring on props within React JS storybooks

I seem to be encountering an issue with destructuring my props in the context of writing a storybook for a story. It feels like there may be a mistake in my approach to destructuring. Below is the code snippet for my component: export function WrapTitle({ ...

Injecting dynamic templates in Angular 7

Let me simplify my issue: I am currently using NgxDatatable to display a CRUD table. I have a base component named CrudComponent, which manages all CRUD operations. This component was designed to be extended for all basic entities. The challenge I am en ...

The FullCalendarModule does not have a property named 'registerPlugins' in its type definition

Currently in the process of integrating fullcalendar into my Angular 15 project and encountering the following error: Error: src/app/views/pages/takvim/takvim.module.ts:18:20 - error TS2339: Property 'registerPlugins' does not exist on type &apo ...

Error in Typescript: The property 'children' is not included in the type but is necessary in the 'CommonProps' type definition

Encountering this error for the first time, so please bear with me. While working on a project, I opened a file to make a change. However, instead of actually making any changes, I simply formatted the file using Prettier. Immediately after formatting, t ...

I am having trouble getting my angular image to switch using angular animations

I am attempting to implement image swapping using Angular animations based on a 10-second timer. However, the swap is not occurring and I have been troubleshooting without success. The goal is for the images to change when the timer reaches 5 seconds, but ...

Utilize the up and down arrow keys to scroll through a description list in React

If you want to navigate through the list of Description Details using the tab and shift tab keys, it can be done easily. The default behavior allows for smooth navigation. <dl> <dt style={{ textAlign: "center" }}>Beast of Bodmin< ...

How do you properly include a new property in an Object using Typescript?

I am currently delving into the world of typescript. After exploring various sources like this one and that one, as well as trying out multiple solutions, I have encountered a challenge. I have a variable named incomingArticleObject which needs to be of ty ...

After executing a query to a PostgreSQL database, I encountered an error preventing me from using res.send(). The error message stated: "Cannot set headers after they are sent to the client."

It may sound strange, but it's a true story. I was busy building an API on node.js when I encountered a peculiar error. As soon as the first res.status().send() was triggered during query processing, VS Code threw a "Cannot set headers after they are ...

Utilizing PrimeNG dropdowns within various p-tree nodes: Distinguishing between selected choices

I am working with a PrimeNg p-tree component <p-tree [value]="treeNodes" selectionMode="single" [(selection)]="selectedNode"></p-tree> The treeNodes are defined using ng-templates, with one template looking li ...

VSCode displaying HTML errors within a .ts file

There is a strange issue with some of my .ts files showing errors that are typically found in HTML files. For example, I am seeing "Can't bind to 'ngClass' since it isn't a known property of 'div'" appearing over an import in ...

Encountered a problem with loading external SCSS files in style.scss using Angular CLI 6 due to issues with postcss-loader and raw-loader in node_modules

ERROR in ./src/styles.scss (./node_modules/raw-loader!./node_modules/postcss-loader/lib??embedded!./node_modules/sass-loader/lib/loader.js??ref--14-3!./src/styles.scss) (Emitted value instead of an instance of Error) CssSyntaxError: /Users/src/assets ...

Encountering a Typescript issue when linking a class component with the reducer

Within my class component that is linked to the redux rootReducer, I am encountering a TypeScript error specifically related to the mapPropsToState section. The error message reads: Property 'unit' does not exist on type 'DefaultRootState&ap ...

How to Add RouterModule to an Angular 10 Library without Ivy

I am developing a custom Angular 10 Library to be shared on a private NPM repository. I followed the instructions from Angular.io and used ng new my-workspace --create-application=false and ng generate library my-library with Angular CLI. In one of the co ...

Error occurs with navctrl when using jquery in Ionic 3

Recently, I started using Ionic framework, I have been integrating jQuery in Ionic to make REST API calls. However, whenever I try to use navCtrl with jQuery, an error pops up in the Chrome console, ERROR TypeError: Cannot read property 'push' ...

Mistakes following update to Angular 4 from Angular 2

After upgrading from Angular2 to Angular4, I encountered these errors in the CLI. While my app continues to function after the upgrade, I am curious about possible solutions to resolve these errors. Any suggestions? https://i.stack.imgur.com/CyYqw.png He ...

Gather keyboard information continuously

Currently working with Angular 10 and attempting to capture window:keyup events over a specific period using RXJS. So far, I've been facing some challenges in achieving the desired outcome. Essentially, my goal is to input data and submit the request ...