JavaScript Variables: let and const Explained
Simply JavaScript variables are used to store data.
Think of a name, age, or score.With let,
you create a variable that can be changed later.
With const, you create a variable that stays the same.
Example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Variables</title>
</head>
<body>
<h1>JavaScript Variables</h1>
<p id=”demo”></p>
<script>
let name = “Peter”;
let age = 18;
const country = “Netherlands”;
document.getElementById(“demo”).innerHTML =
“Name: ” + name + “<br>” + “Age: ” + age + “<br>” + “Country: ” + country;
</script>
</body>
</html>
Explanation
In this example, 3 variables are created:
- name with the value “Peter”
- age with the value 18
- country with the value “Netherlands”
After that, these values are shown on the web page.
The difference between let and const
Use let when the value may change later.
Use const when the value should stay the same.
