Recent Post:
Categories:
September 21, 2024
181
Think you know it all?
Take quiz!Explanation:
In JavaScript, we use const, let, and var to create variables—those special boxes we talked about. But each one works a little differently, like different types of containers for different jobs.
1. var: This is the oldest way to create a variable. It can be used anywhere in the program, even outside the place where it was created. It’s like a box that can be seen
2. let: This is a newer way to create a variable. It can only be used in the specific area where you created it. Think of it like a box you put in a drawer—it can’t be seen outside that drawer.
3. const: This is another way to create a variable, but it’s special because you can’t change what’s inside the box after you create it. It’s like a sealed jar; once you close it, you can’t take anything out or put anything else in!
code
var name = "Satyendra"; // This is a var variable
if (true) {
var name = "Alice"; // This reuses the same variable
console.log(name); // Output: Alice
}
console.log(name); // Output: Alice (changed outside the block)
Here, we first create a var variable called name with the value "Satyendra." Inside the if block, we use var again to change name to "Alice." When we log name outside the block, it shows "Alice" because var can be accessed from anywhere, even outside the block where it was changed.
code
let age = 10; // This is a let variable
if (true) {
let age = 15; // This creates a new variable just for this block
console.log(age); // Output: 15
}
console.log(age); // Output: 10 (the original value remains unchanged)
We create a let variable called age with the value 10. Inside the if block, we create a new age variable that only exists inside this block and set it to 15. When we log age inside the block, it shows 15, but outside the block, it still shows 10 because let keeps it safe inside its drawer.
code
const pi = 3.14; // This is a const variable
console.log(pi); // Output: 3.14
// pi = 3.14159; // This would cause an error because we can't change const variables
We create a const variable called pi and give it the value 3.14. When we try to log pi, it shows 3.14. If we try to change pi later, like setting it to 3.14159, it will cause an error! This is because const means we can’t change what’s inside the box once we seal it.