Introduction
JavaScript is a language of Web. This series of articles will talk about my observations learned during my decade of software development experience with JavaScript.
In the last article I covered anonymous function. In this article I will cover pure and impure function in detail. Before I cover this, we should understand some aspects of functional programming so we know what is mutable and immutable objects.
Before moving further let us look at the previous articles of the series:
- Voice of a Developer: JavaScript Data Types - Part One
- Voice of a Developer: JavaScript Objects - Part Two
- Voice of a Developer: JavaScript Engines - Part Three
- Voice of a Developer: JavaScript Common Mistakes - Part Four
- Voice of a Developer: Editors - Part Five
- Voice of a Developer: VSCode - Part Six
- Voice of a Developer: Debugging Capabilities of VSCode - Part Seven
- Voice of a Developer: JavaScript OOP - Part Eight
- Voice of a Developer: JavaScript Useful Reserved Keywords - Part Nine
- Voice of a Developer: JavaScript Functions - Part Ten
- Voice of a Developer: JavaScript Functions Invocations - Part Eleven
- Voice of a Developer: JavaScript Anonymous Functions - Part Twelve
Functional programming
Mutable
Example
- var y={a:1, b:2};
- var x =y;
Immutable


Pure function
These are the functions that always return the same value when given the same arguments. They take some parameters, return a value based on these, but don’t change parameter values. An example product is a function that will always give the same output depending upon the input.
- function product(a, b) {
- return a * b;
- }
- console.log(product(2, 3));
- // always give 6 whenever you pass 2, 3
Example
- var x = 10;
- function pureFunction(a) {
- return a + 2;
- }

Impure function
Example
- var count = 0;
- function Hits() {
- count += 1;
- }
- Hits(); // will make count 1
- Hits(); // will make count 2
- Hits(); // will make count 3
Here it's using an external variable count and also modifying it. If a function has side effects whether it updates any file or database it’ll also fall under the category of impure function.
- function impureFunction(a) {
- file('update.txt');
- }
Summary of differences
| Pure function | Impure function |
| No side effects like update or DB calls | May have side effects |
| Don’t modify arguments which are passed to them | May modify arguments passed to them, |
| Always return the same value | Even if you call with the same arguments, you may get different values. |
I hope you enjoyed reading the article. Please share your comments or feedback.
Kuppurasu NagarajPosted May 9, 2016, 12:16 PM
Nice Sharing..