Arrow Functions doubt

Arrow Functions doubt

I am new to Javascript and learned about function expressions, anonymous functions, arrow notations, etc today. I have a doubt.

" When there is no function body, and only a return value, arrow function syntax allows you to omit the keyword return as well as the brackets surrounding the code. This helps simplify smaller functions into one-line statements:

const myFunc = () => “value”


So, invoking this function just returns “value”. My question is: how is this different than just using a variable to store “value”? What are the differences between the two approaches? Pros and cons?

In real life you probably wouldn’t write a function that just returns an arbitrary string like that. A getter function, however, would be pretty simple. Also, remember that logic can be performed in a return statement.

const canIVote = (age) => age >= 18 ? "yes" : "no";
1 Like

Ah yes, that makes sense. Thanks :slight_smile:

The aprop solution was already said: you return an expression.

Since a value is also an expression that evaluates to itself, then a single value it’s also a valid case in the following scenarios

1- As a getter

const getColor = () => this.color

2- As a value provider (concept introduced in functional programming. There are many useful providers that can be used in functional composition.

2.1 - Identity function that returns whatever you pass to it

const identity = (x) => x

This doesn’t make sense at first but functional programmers use it for cases like the following:

import { identity, filter } from 'ramda'

// curried function that expects a list to be passed
// identical al saying:
// const falsyBouncer = (xs) => xs.filter(x => x)
const falsyBouncer = filter(identity)

falsyBouncer([2, false, 3, '', 'hello', NaN, null, []])
//> [2,3,'hello',[]]

2.2 - Values to supply in a pipeline or composition chain

const false = () => false
const objectFactory = () => new MyClass(...args)
const zero = () => 0 // trust me, people use this
// etcetera

2.3 - A function that does nothing and receives nothing and returns nothing, it’s has a technical name called “no op” (no operation):

const noop = () => undefined // lodash or jquery
const noop = Function.prototype // don't ask, I don't know myself
const noop = () => {} // answered as the fastest one

2.4 - Boolean negation

const negate = (x) => !x

2.5 - A function that always returns the value that you specified using curried function no matter how you call it.

// 'constant' is often aliased to 'always'
const constant = (x) => () => x

This one can be used as a supplier builder, I’ve seen it used before but I haven’t personally used it.

You’ll often use some of these but you can always rely on other methods.