Var VS let VS const
Var is used in either local variables or global variables. We will understand it with a simple example. We assume that we have slightly understood the basic concept of Var. Let’s now jump in to the code to make our concept clearer.
var x=”I live in Pakistan”
console.log(x) // Printing variable x
console.log(x) // printing to see the result
Console.log(x) // Printing variable xPrint x to see the result.
Over-writing the variable x which was previously as “I love Pakistan”. There will be no error and it will be over-written. Thus, we came to the point that declaring variable with var can be over-written. Thus, during practical development the variable or a value that has to be updated time to time is used and declared with Var.
‘Both var and let work almost same as the var does work but the difference is a very slight but that creates a major distinguish between let and var.
Unlike var you can not declare the variable multiple times. For example In above example variable x was declared at the top as var x. later, the variable x was again used with var declaration. No error was shown and result was shown on the screen but when you are working with let you can not update it the way you had the privilege in using var. For example
let x= “Hello world”
let x=” Welcome ”
console.log(x)//Print on console
In above example I tried to use let with the same variable name to over-write it will throw an error “Re-declaring the variable already used“. So, you can’t do it in this manner.
Isn’t there any other way to complete it or execute it?
Yes, here it is.
let x= “hello world”
now, We did the same work as we did in var but with a slightly different way. So, From this point it has been a clear understanding that var and let are almost same but just a slight difference.
Unlike var and let, Const works in a very different manner and way. All such values that you do not want to change through out your development and usage of the product you declare it as const. For example value of pi is 3.14 and is never gonna be changed so I will declare it as constant if I wished to use it in my program so it can’t be changed or updated.
For an instance we are going to understand it with the help of coding stuff and hope it would then be more understandable.
x=15; //Trying to update const value
We won’t be able to change the value of x as it is now declared as const. If we change the const to let or var we would no longer than get error but our aim will not be justified then because we do not want to update the values used as const.
I hope you’d have got the very clear idea of let const and var. Please comment down the question below if you still find it difficult.
Buy on amazon with upto 40% off