coding javascript memo

How to use Basic Arrow Functions

Some quick examples of how to use the new ES6 arrow function syntax to replace function()

28 Jan, 2023

I found this video about arrow functions and it's examples super helpful so just summing it up here for my own understanding and future reference.

(Unrelated personal note: Looks like I need to figure out something with JavaScript SDK to get video embeds working... lots to sort out and learn! @_@;; )

Video URL: https://youtu.be/h33Srr5J9nY

Example 1

This...

function sum(a, b) { return a + b }

..becomes this

let sum = (a + b) => a + b

  • When using function(), "sum" is a variable that implicitly defined, so when using arrow function we need to define it using a keyword like let

  • when on a single line, the part after the arrow is implied as the return statement so you can omit writing return

Example 2

This...

function isPositive() { return number >= 0 }

..becomes this

let isPositive = number => number >= 0

  • the part before the arrow is the variable you are passing in, if this is a single variable then the brackets can be omitted

Example 3

This...

function randomNumber() { return Math.random }

..becomes this

let randomNumber = () => Math.random

Example 4

This...

document.addEventListener('click', function() { console.log('click') }

..becomes this

document.addEventListener('click', () => console.log('click')

The keyword this in arrow functions

  • The treatment of this keyword is different in arrow functions and regular functions

  • Regular functions will redefine this based on where the function has been called, for example if it is run in the global scope then this is based on the global scope

  • In an arrow function, this does not get redefined but stays exactly as it is in the function it is defined in, which is how it is in most other programming languages

The treatment of this