Imagine Variables and Immutability

Imagine Variables and Immutability

Complex JavaScript World

Β·

6 min read

Variables are core concept in JavaScript. They provide you ability to store values, functions, objects, etc in memory. But the simplicity of concept is their curse. People often misinterpret their application and differences between different types of variables. Over the course of my studies, I have encountered few difficulties with variables and what is the difference between.

Let's have a look, what are they? What is the difference and how to use them? Let's imagine JavaScript Variables!

Meet Variables πŸ‘‹

brothers-js.png

Imagination ON🌈

Have you heard of Variables family? No? No problem! Welcome, three brothers: Vartan, Letan and Constan. They call themselves var, let and const respectivelyπŸ™Œ

Variables family is one of the most important pillar of whole JavaScript world. They work at JavaScript warehouse called Memory.

Three brothers are working day and night to store goods, information and data you provide them. They will label it and store in different cells depending on the size of data.

For the sake of organisation of data stored, labels - are unique names.

So if they do same job, are they same? Well...πŸ‘€

Yeah, that's kind of right. They do have same responsibilities, but the way they do things is different.

var is the oldest brother of three. He was the one who started this family business. He has some issues though. var is very careless 😬 People often got frustrated with his behavior.

When people come to declare their data to be stored in the warehouse, with var they can declare data with same name, which leads to a mess.

He would store some data in the warehouse, label it and if somebody else would try to use same label name for other data - he would do it without hesitation.

Can you imagine how frustrated people get when their stuff is missing?! var doesn't even feel guilty. That's just the way he is.

Luckily new brothers were born. let and const have become such a relief for everyone, cause they finally do the job properly. People even abandoned var, that's how bad he was. Nobody wants to work with him anymore πŸ˜₯

let and const do care about unique identifiers as labels and therefore won't allow you to declare data to store with name used before. But, they have their own personalities too.

let will still give you ability to access stored data and replace it with something else, but nobody can declare data using old name.

const is the strictest of three. Once people declared data to be stored, nobody can replace it with anything else.

Imagination OFF

Hope you enjoyed this short introduction to Variables family. Now, let's get to work!

Variables

What are variables? Variables are unique names we use to store data in the memory. Every time you are declaring a variable, memory allocates space for it and names that space with variable name you provide.

We will talk about Memory in future articles.

There are three (!) ways to declare variables in JavaScript. Using three different keywords: var, let and const. All of them are used to store data, let's see what's the difference then.

var

var was the only way to declare variables before ES6 update. varis function scoped - can be used everywhere within function and it's affected by Hoisting - can be accessed at the beginning of the script even if value was declared at the end of it.

Let's take a look at example.

Since var has a function scope it is being reassigned every iteration of the loop. When loop is over, i becomes 3, as it is required to pass last conditional statement before termination of the loop and it affects all use of i within that function.

Another example, now let's look at Hoisting.

As you can see, the endOfScipt variable was accessed and it's value is undefined. This is an example of Hoisting.

Check Imagine Execution Context and Hoisting for more information what's happening at this phase.

The main issue with var was that you could redeclare variables. Combined with Hoisting and huge code bases you can imagine to what kind of mess it could lead.

let and const

After arrival of ES6 specification update let and const have been introduced. The main benefit was that variables can't be redeclared anymore.

I like this short and sweet explanation of differences between let and const given by @robertbalazsi

Variables declared with let and const have block scope, which means scope between { } braces.

Take a look at example with var and let.

Here, since let was declared inside { } braces, it was scoped to that block and is not accessible outside of it.

let and const are serving same purpose in the matter of scope, but const is also preserving the data stored. Values declared with const can't be replaced.

let a = 5;
const b = 10;

a = 'soup';
b = 'coffee'; //Uncaught TypeError: Assignment to constant variable.

Mutability

Let's just touch the tip of the Mutability and Immutability in this article. There are mutable and immutable values, means that some of the values can be not changed, but modified, mutated.

For example string and number are immutable values. We often get confused when we are using something like:

let a = 10;
a++;

Are we mutating number value? Actually, we are not. The example above is just syntactic sugar we use for short way of writing following:

let a = 10;
a += 1; //this is still syntactic sugar by the way

//Full form will be

let a = 10;
a = a + 1; //this is full form of writing a++

As you can see, we are not changing the number value itself, because it is immutable, but we are reassigning it to the same variable a

Even more confusion causing use of const

const is not making value immutable. It is just making sure that you cannot reassign anything to the variable.

const a = 10;
a++ ; // Uncaught TypeError: Assignment to constant variable.

So which values are mutable then? Let's take this simplest data structure we are all using often - arrays.

const array = [1, 2, 3, 4];
array = [5, 6, 7]; // Uncaught TypeError: Assignment to constant variable.

//BUT

const array = [1, 2, 3, 4];
array[3] = 10;
console.log(array); // [1, 2, 3, 10]
array[4] = 'cat';
console.log(array); // [1, 2, 3, 10, "cat"]

The value can't be replaced by another value, but it can still be modified. This is the characteristics of mutability.

Summary

This one was long eh? πŸ˜…

Variables are important to understand and know how to use them. As usual, while writing this blog post I have also learned something new together with you. Please don't forget, always check docs and references.

Hope you have enjoyed it 🀞

In case you found something contradicting or wrong information please contact me or leave comments. Thank you πŸ™

P.S. by the way you can find me on Twitter @SergiiKirianov πŸ‘€

References

Did you find this article valuable?

Support Code Cry Repeat by becoming a sponsor. Any amount is appreciated!

Β