JavaScript Variables
A variable is a named box that stores a value. You can use the name later to read or change the value.
let name = "Robin";
let age = 25;
console.log(name);
console.log(age);
Output of the above program is
Robin
25
let, const and var
| Keyword | Can change value? | Scope | Use |
|---|---|---|---|
let | Yes | Block | For values that change |
const | No (cannot be reassigned) | Block | For values that stay the same. Use it by default |
var | Yes | Function | Old way. Avoid in new code |
let
let score = 10;
score = 15; // allowed
console.log(score);
Output of the above program is
15
const
const PI = 3.14159;
PI = 3; // TypeError: Assignment to constant variable.
Output of the above program is
TypeError: Assignment to constant variable.
const stops you from reassigning the variable. If the value is an object or an array, its inside items can still change.
const colors = ["red", "green"];
colors.push("blue"); // allowed
console.log(colors);
Output of the above program is
[ "red", "green", "blue" ]
Naming rules
- Start with a letter,
_or$. - Use camelCase:
userName,totalPrice. - Do not use keywords like
letorclass. - Choose clear names:
ageis better thana.
Declare many variables
let x = 5, y = 10, z = x + y;
console.log(z);
Output of the above program is
15
Note:
A good habit: use const first, and change it to let only when you know the value must change.
Summary
- Declare variables with
let(changeable) orconst(fixed). - Avoid
var. - Learn where variables can be used in JavaScript Scope.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| Write a JavaScript program to add two numbers |
| Write a JavaScript program to swap two variables |