Defining Variables; using (const, let and var)
Const
Is used to declare a variable that cannot be re-assigned after it has been defined. It is useful for declaring constants or values that should not be changed.
Let
Is used to declare a variable that can be re-assigned. It is useful for variables that may change in value during the execution of a program.
Var
Is also used to declare a variable that can be re-assigned. However, it has some differences in scoping compared to let
and const
. It is recommended to use let
and const
instead of var
in modern JavaScript. It's somehow deprecated.
Examples
<html>
<script>
- Using const
const firstname = "Dickens";
console.log(firstname);
firstname = "Eve";
This throws a type error which means we are assigning a new value to a constant/value that can't change.
2 . Using var
var a =12;
var b = 25;
var c = a + b;
var sl = "My name is ";
var firstname = "Bill";
console.log("a + b = " + a + b);
console.log("c = " + c);
console.log(sl + firstname);
In this example, we have a = 12, b = 25 and c as the sum of a and b. We’ve got sl and firstname as strings. The first output gives 1225, which means when we started with quotes that meant to JavaScript that the rest is a character string hence it didn’t add instead it concatenated the values, concatenation means linking together. The second output is 37 and the last output will be “My first name is Bill”.
- Using let
var a =12;
if (true) {
var b = 22;
let c = 66;
console.log("In the brace:");
console.log("a = " + a)
console.log("b = " + b)
console.log("c = " + c)
}
console.log("After the brace:")
console.log("a = " + a)
console.log("b = " + b)
console.log("c = " + c)
We have defined a variable a = 12 as global and its accessible anywhere to this block of code, the fist output of this will be ;
In the brace:
a = 12
b = 22
c = 66
This means that variable a is still accessible even in the braces and ofcourse the rest are also accessible.
The second output ;
After the brace:
a = 12
b = 22
Uncaught ReferenceError: c is not defined
This time we run into an error after our first two succesful outputs. This error says c isnt defined , this is because c isnt defined outside the braces, its only defined in the braces and it remains there and only accesible there ALONE.
var b is also accesible to outside , this shows how powerful var is as compared to let.
</script>
</html>
Subscribe to my newsletter
Read articles from Shaki directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Shaki
Shaki
A Full-stack Developer based in Nairobi Kenya , with a focus on creating robust and user friendly web applications. With strong foundation in both front-end and backend development, I specialize in building responsive and scalable solutions that deliver exceptional user experiences.