Sunday small thread about JavaScript functions 👇🏼

A function can be defined in 2 ways:

function() {
....
}

(regular functions) I call them "regular" because they are there since the early days of JavaScript

or

() => {
....
}

(arrow functions) introduced around 2015
There are some differences.

In the first case, we can give the function a name without assigning it to a variable:

function go() {
....
}

but we can also assign them to variables:

const go = function() {
...
}
while arrow functions can only be assigned to a variable if you want to give it a name

const go = () => {
....
}

But the big difference is how `this` works, and this is crucial when using them as object methods.
Arrow functions allow you to have an implicit return: values are returned without having to use the return keyword.

It works when there is a one-line statement in the function body:

const go = () => 'test'

go() //will return 'test'
Both function formats accept parameters inside the parentheses, but in arrow functions if we have one parameter, we can omit the parentheses:

const go = param => {
console.log(param)
}

go('hey')
Methods example:

const car = {
brand: 'Ford',
model: 'Fiesta',
start: function() {
console.log(`Started ${this.brand} ${this.model}`)
},
stop: () => {
console.log(`Stopped ${this.brand} ${this.model}`)
}
}
`this` in the start() method refers to the object itself.

But in the stop() method, which is an arrow function, it doesn’t.

It points to what this points to in the outer scope.

Arrow functions are not suitable to be used as methods when you want to access the object instance
You can follow @flaviocopes.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled: