JavaScript Variables
JavaScript variables are used to store data values. Variables allow you to save information such as names, numbers, and text, which can be used later in your program.
What are Variables?
A variable is like a container that holds a value. In JavaScript, you can create variables
using the var, let, and const keywords.
let– used for variables that can changevar– older way to declare variablesconst– used for variables that cannot be changed
JavaScript let Variable
The let keyword is used to declare variables that can be updated later.
It is the most commonly used keyword in modern JavaScript.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let name = "John";
document.getElementById("demo").innerHTML = name;
</script>
</body>
</html>
Try this code
JavaScript var Variable
The var keyword is the older way to declare variables. It can still be used,
but it is not recommended for modern JavaScript development.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var city = "London";
document.getElementById("demo").innerHTML = city;
</script>
</body>
</html>
Try this code
JavaScript const Variable
The const keyword is used to declare variables whose value cannot be changed.
Once a value is assigned, it remains constant.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const age = 25;
document.getElementById("demo").innerHTML = age;
</script>
</body>
</html>
Try this code
JavaScript Multiple Variables Example
You can also combine multiple variables together to display complete information. This is commonly used in real-world applications.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let name = "John";
const age = 25;
var city = "London";
document.getElementById("demo").innerHTML =
name + " is " + age + " years old and lives in " + city;
</script>
</body>
</html>
Try this code
Rules for Naming Variables
- Variable names must begin with a letter, $ or _
- Variable names are case-sensitive
- Do not use JavaScript keywords as variable names
Best Practices
- Use
letinstead ofvar - Use
constfor values that should not change - Choose meaningful variable names