Back to all questions

What is a pure function?

Devs Hive

Devs Hive

Seen on interview: 0 users

A pure function is a function that always returns the same result for the same input and has no side effects. The definition can be confusing, so let's go through examples of each of these characteristics:

The same result for the same arguments

// Ця функція чиста, так як працює тільки з своїми аргументами
// і викликавши її в будь якому місці нашого додатку,
// результат виконання не зміниться,
// так як функція не залежить від зовнішніх умов
const applyDiscount = (price, discountPercent) => {
return price - (price * discountPercent) / 100
}
// ----------------------------------------------------------------

// В цьому прикладі функція залежить від DISCOUNT_PERCENT
// і якщо його значення зміниться, результат виконання буде інший
// тому така функція не може вважатись чистою
const DISCOUNT_PERCENT = 20;

const applyDiscount = (price) => {
return price - (price * DISCOUNT_PERCENT) / 100
}

No side effects

A function has no side effects if it does not modify external variables, objects, files, the DOM, databases, or network resources.

// Ця функція НЕ чиста, так як вона взаємодіє з API і залежить від нього.
const fetchUser = async (id) => {
const response = await fetch(`https://api.example.com/users/${id}`);
return response.json();
};

To make your answer sound more professional, you can add that this technique is widely used in programming, both on the backend and on the frontend. It is good form to give 1-2 examples from the framework you use, for example React.js, Nest.js, Angular, etc. It is also worth mentioning that using this concept makes writing Unit and Integration tests easier.

Seen on interview?

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!