DEV Community

Cover image for Pure Function in JS
Ustariz Enzo
Ustariz Enzo

Posted on • Edited on

9 2

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.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

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 😬

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay