JavaScript the Fun Part


functional-programming-javascript

immutable-and-mutable-data


These two terms are very close to the two previous terms

  1. pure funciton
  2. impure function

not just conceptually, but also in practice.

Mutability

Mutable data refers to changeable data over time. We store our data in a variable and that variable which acts like a container for that data type is modified over and over again. The best example is a for loop

let index = 0;
const max = 10;
for( ; index < max; ++index ){
    console.log( "index:", index );
}

Here index is overwritten in each for loop iteration. We need this mutability. But for many cases we do not need mutable data e.g. max variable. Since when our data is constant, two things happen

Thus in any cases that we do not need to modify (= update) a variable it is better to explicitly declare it as constant.

Immutability

The opposite of mutable data is immutable data. Data that cannot be changed and we should not be modify them.

In practice (coding) immutable data are differentiated using const keyword which tells the interpreter (or compiler) this is a constant variable.

For constant variable the declaration part and assignment happen at the same time which is a big difference between non-constant variables that can be declared first and then be assigned or reassigned again and again.

Thus, constant variables are one time assignment operations while non-constant variables are many times assignment operations.

Pure & impure functions

From the previous post and this one you can see there is a similarity between pure function - function that should not change the state of our application - with immutable data that prevents our states from changing.

Also impure function - function that modifies states of our application - with mutable data that holds data that are changed over time in our application.

So instead of writing a code this way

// data 
let year = 2019;

// impure function
function inc(){
    ++year;
}

// impure function
function dec(){
    --year;
}

We will refactor it to this one

// data 
const year = 2019;

// impure function
function inc( input ){
    ++input;
}

// impure function
function dec( input ){
    --input;
}

Or in ES6 style

// data 
const year = 2019;
const add = x => ++x;
const dec = x => --x; 

Thus as much as we can, we prefer

over

The combination of

helps us to have a side effect free morphism which will be our next post's topic.


Update: Sun Nov 10 2019 08:36:37 GMT+0330 (Iran Standard Time)