Pure Function in JS
Ustariz Enzo
Posted on December 14, 2021
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
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
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.
Posted on December 14, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 28, 2024