HTML CSS JAVASCRIPT PYTHON JAVA

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.

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.

Example
<!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.

Example
<!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.

Example
<!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.

Example
<!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

Best Practices