DEV Community

Cover image for Pure Function in JS
Ustariz Enzo
Ustariz Enzo

Posted on • Updated on

Pure Function in JS

Hey fellow creators

Let's learn what a pure function does in less than a minute!

If you prefer to watch the video version, it's right here :

1. What's a pure function?

A pure function is a function that returns the same result every time we use the same arguments. They also have no side effects, meaning that it doesn't change anything outside of the function.

2. Let's take a look at a function... is it a pure function or not?

The following function will change something outside of the function (the variable a) and it will not return the same result:

let a = 5;

const add = num1 => {
    a += num1;

    return a;
}

console.log(add(5)); // 10
console.log(add(5)); // 15 
console.log(add(5)); // 20
console.log(add(5)); // 25
Enter fullscreen mode Exit fullscreen mode

3. Let's take a look at a pure function then.

Let's create the following function that will not change anything outside of the function and will return the same result:

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

console.log(add(5,5)); // 10
console.log(add(5,5)); // 10
console.log(add(5,5)); // 10
console.log(add(5,5)); // 10
Enter fullscreen mode Exit fullscreen mode

Now you know what a pure function is? Well done!

Come and take a look at my Youtube channel: https://www.youtube.com/c/TheWebSchool

See you soon!

Enzo.

Top comments (2)

Collapse
 
shadowruge profile image
izaias

Simples e direto

Collapse
 
ruisilva profile image
Rui

Everything fine except that hero image and video thumbnail showcase invalid syntax 😬