What is functional programming in JavaScript?

Functional programming is a programming paradigm that allows us to use declarative programming (telling what to do) rather than imperative (how to do). In practice, this means that functions are composable, first-class variables, and transform inputs immutably. In JavaScript, arrays contain methods that allow for immutable transformations using callbacks. These come in handy for writing clean and concise code without needing for loops.

Arrow Functions

Arrow functions are an alternative way to write functions as a first-class variable.

const sum = (a, b) => a + b;

// sum(a, b) takes in two variables, calls the "+" operator, and then returns the result
// automatically

They are similar to regular functions but they lack some key attributes such as an implicit "this" keyword (see here for more). There is also some additional interesting syntax with specific use cases.

To write more than one line of code for an arrow function, wrap the code in curly braces as you would with a normal function.

const fetchData = async () => {
	const people = await fetchPeople();
	people.forEach(console.log);
}

To return a value directly, wrap it in parenthesis.

const newUser = (name, age) => ({
	name,
	age,
	created: new Date()
})

If the function you are defining has only one parameter, you may omit the parenthesis

const capitalize = s => (s && s.length > 0) ? s[0].toUpperCase() + s.substring(1) : null;

Array Methods

Listed below are commonly used array methods. All array methods can be found on the Mozilla Reference page.

.forEach()

The .forEach() function calls the provided callback function on each element of the array. Notably, it does not return a new instance of the array as .map() does.