In JavaScript, there are three types of variables: 1. var: The var keyword is used to declare a variable in JavaScript. It has function scope, meaning it is accessible within the function where it is declared. If var is declared outside any function, it becomes a global variable and can be accessed throughout the entire program.
var x = 5; // declaring a variable 'x' and assigning a value of 5
- let: The
letkeyword was introduced in ES6 (ECMAScript 2015) and it also declares a variable, but with block scope. Variables declared withletare only accessible within the block where they are defined, such as within a loop or an if statement.
let y = 10; // declaring a variable 'y' and assigning a value of 10
- const: The
constkeyword is used to declare a constant variable, which cannot be reassigned after its initial value is set. Likelet,constalso has block scope. It is commonly used for values that should not be changed, such as mathematical constants or configuration settings.
const z = 15; // declaring a constant variable 'z' and assigning a value of 15
Here’s an example of using these variable types in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Variable Types in JavaScript</title> </head> <body> <script> // Using var var x = 5; document.write("Value of x: " + x + "<br>"); // Using let { let y = 10; document.write("Value of y: " + y + "<br>"); } // Using const const z = 15; document.write("Value of z: " + z + "<br>"); // Trying to reassign a constant variable (will throw an error) // z = 20; </script> </body> </html>
When you run this HTML file in a browser, it will display the values of x, y, and z as 5, 10, and 15 respectively. Note that if you uncomment the line z = 20;, it will throw an error because you cannot reassign a constant variable.