JavaScript Variables
A variable is a named container that stores a value, so you can use it again later.
Creating a Variable
Use the keyword let, a name, the = sign and a value:
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let studentName = "Ayesha";
let age = 19;
document.getElementById("demo").innerHTML = studentName + " is " + age + " years old.";
</script>
</body>
</html>Try it Yourself »Ayesha is 19 years old.
The = sign in JavaScript does not mean "equal to". It means assign: put the value on the right into the variable on the left.
Three Ways to Declare
| Keyword | Can change later? | When to use |
|---|---|---|
const | No | Values that should stay the same |
let | Yes | Values that will change |
var | Yes | Old code only; avoid in new code |
Using let
A let variable can get a new value later:
Example
let balance = 1000;
balance = balance - 300; // Ali spent Rs 300
console.log(balance);700
You can create a variable without a value. Its value is then undefined until you assign one.
Example
let city;
console.log(city); // undefined
city = "Lahore";
console.log(city); // LahoreUsing const
A const variable must get a value when it is created, and it cannot be given a new value.
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const courseFee = 4500;
const months = 3;
const total = courseFee * months;
document.getElementById("demo").innerHTML = "Total fee: Rs " + total;
</script>
</body>
</html>Try it Yourself »Total fee: Rs 13500
Trying courseFee = 5000; later would cause an error: "Assignment to constant variable".
A simple rule many developers follow: use const by default, and switch to let only when you know the value has to change.
Block Scope
Variables made with let and const only exist inside the { } block where they are created.
Example
let message = "outside";
{
let message = "inside";
console.log(message); // inside
}
console.log(message); // outsideThe old keyword var does not respect blocks, which causes confusing bugs. That is why modern code uses let and const.
Declaring Many Variables
You can declare several variables in one statement, separated by commas:
Example
let item = "Chai", price = 60, cups = 2;Naming Rules
- Names can contain letters, digits, underscores
_and dollar signs$ - Names must not start with a digit
- Names are case sensitive (
priceandPriceare different) - Keywords like
let,iforreturncannot be names
Choose names that describe the value: totalMarks is much clearer than x.
Exercise
Exercise
What happens if you run: const pi = 3.14; pi = 3;
