JavaScript Variables
JavaScript variable is a container that can hold a value, such as a number or a string. Variables are declared using the var, let, or const keywords.
Here's an example of declaring a variable using the var keyword:
javascript var x = 2;This declares a variable named x and assigns it the value of 2.
The let and const keywords provide additional features for managing variables.
With let, you can declare a variable that is block-scoped, which means it only exists within the block of code where it was declared. For example,
javascript let y = 100;
if (true) {
let y = 20;
console.log(y); // output: 20
}
console.log(y); // output: 10In this example, you declared a variable named y and assigned it the value of 100. Within the if statement block, we declare another variable also named y and assign it the value of 20. This new y variable only exists within the if block, so when we log its value, it outputs 20. When we log the value of y again outside of the if block, it outputs 100, which is the value of the original y variable.
The const keyword declares a variable that is also block-scoped, but it cannot be reassigned once it has been declared unlike the Let variable. For example,
javascriptCopy codeconst z = 15;
z = 20; // This will throw an errorIn this example, you will declare a variable named z and assign it the value of 15. When you try to reassign it to 20, you will get an error because z is a const variable and cannot be reassigned.
Last updated