In any programming language, variables are named containers containing any type of data at a specific memory location. The name of every variable must be unique.
In JavaScript, we can create a variable in 3 ways :
- using var -
var name; // only declaration
var fname = Ansh; // declaration and initialization
- using let -
let name; // only declaration
let fname = Ansh; // declaration and initialization
- using const - We cannot use const without setting a value. i.e. const can't be undefined.
const name = Ansh; // declaration and initialization
We can use any of the above ways to declare variables. But is there any difference between these? let's see
- Var is function scope but let and const are block scope.
<html>
<head>
<title>let vs const vs var</title>
</head>
<body>
<script>
function cart(){
var item1 = "milk";
console.log(item1);
if(true){ //let and const life exist only in this block.
const budget= 500;
let item2 = "butter";
console.log(budget);
console.log(item1);// var can be accessed here
}
console.log(item2);// we can't access item2 here because it is accessible only in 'if' block. This line will give error.
}
cart();
</script>
</body>
</html>
OUTPUT:
- We can't change the value of const but let and var values can be updated.
<html>
<head>
<title>let vs const vs var</title>
</head>
<body>
<script>
let myName="Ansh";
var myAge=22;
myName="Shriansh";// No need to declare again
myAge=21;// No need to declare again
console.log(myName);
console.log(myAge);
</script>
</body>
</html>
OUTPUT: You can see the updated values on the console.
<html>
<head>
<title>let vs const vs var</title>
</head>
<body>
<script>
const myFname="Shriansh Kumar";
myFname="Kumar";
console.log(myFname);
</script>
</body>
</html>
OUTPUT: It will give an error.