JavaScript Variables Declaration- How to Declare Variables in JavaScript?

In JavaScript declaring a variable means to create a variable. You need to write its type and assign it a value in JS. You can find many tutorials and videos where developers are trying to explain the difference and they are incredibly good. I am not telling you anything new or better. I am just trying to explain this with my example. Maybe this will increase your understanding. 

There are 3 ways to declare a variable in JavaScript. 

var num = 3 

let num = 3

const num = 3 

Let’s say you are writing a piece of code in JavaScript and you declared a variable like this. 

var num = 3

Now num is not a unique way to represent ‘number’ and we coders mostly use ‘num’ to represent ‘number’ in our code. You pushed the code to git and some other guy pulled your code and started working on it. Now he declared a variable like this.

var num = 5

Guess what! JavaScript will allow him to do so. With the keyword ‘var’ you can declare variables with the same name as much as you want. But this is not a convenience. It can break your code. I don’t know why they allowed it in earlier versions of JS. Maybe they think that JavaScript will never be written more than 10 lines so people could easily locate where they are redeclaring the variable. Anyways, to tackle this problem JavaScript has another way of declaring variable with the keyword ‘let’. 

let num = 3

If we write this then we can never be able to declare any variable with the same name in that scope again. This is how most programming languages work. But wait a minute. In most programming languages if we declare a variable then we also define its type. But in JS using ‘let’ there is another problem. We can write 

let num = 3

And then if we check the type of num by using typeof keyword then it will show the type as number. But if we assign this variable some string value 

num = ‘3’

Then guess what! JS is allowed to change the type of the variable. Now num is of string type. This behavior is not so harmful when we are dealing with variable types like string or numbers. But when it comes to arrays and objects then it can break the code entirely. Let me give an example. You declared an array like this. 

let ages = [3,5,4,2,6]

Now some other coder can write something like this. 

ages = 4 

And now all the values in the array are gone. The variable was of type array but now its type is number. Now this is why whenever JS coders want to deal with arrays, objects or functions they try to use ‘const’ rather than ‘let’.

const getAges =  (e) => {

// some code … 

}

I hope this will increase your understanding about declaring variables in JS. If you have any questions then feel free to comment. We will appreciate that.Â