Pure Function in JS
source link: https://dev.to/ziratsu/pure-function-in-js-3heb
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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/Learntocreate/videos
See you soon!
Enzo.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK