Function Expressions & Arrow Functions

Function Expressions

Example

Functions are values: they can be stored in variables, passed to other functions and returned:

const square = function (x) {
  return x * x;
};
function applyTwice(fn, value) {
  return fn(fn(value));
}
console.log(square(4));
console.log(applyTwice(square, 3));

Output

16
81

Arrow Functions

Example

A shorter syntax. With a single expression, the braces and return can be dropped:

const add = (a, b) => a + b;
const double = n => n * 2;
const makeUser = (name) => ({ name, createdAt: "2024-06-01" }); // wrap objects in ()
console.log(add(2, 3), double(21));
console.log(makeUser("Kavya"));
console.log([1, 2, 3].map(n => n * 10));

Output

5 42
{ name: 'Kavya', createdAt: '2024-06-01' }
[ 10, 20, 30 ]

Arrow Functions and this

Arrow functions do not have their own this; they use the this of the surrounding code. That makes them ideal for callbacks, but they should not be used as object methods that need this (see Objects and Advanced Functions).