JavaScript Tutorial menu

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

html
<!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 »
Output
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

KeywordCan change later?When to use
constNoValues that should stay the same
letYesValues that will change
varYesOld code only; avoid in new code

Using let

A let variable can get a new value later:

Example

javascript
let balance = 1000;
balance = balance - 300;   // Ali spent Rs 300
console.log(balance);
Output
700

You can create a variable without a value. Its value is then undefined until you assign one.

Example

javascript
let city;
console.log(city);   // undefined
city = "Lahore";
console.log(city);   // Lahore

Using const

A const variable must get a value when it is created, and it cannot be given a new value.

Example

html
<!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 »
Output
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

javascript
let message = "outside";
{
  let message = "inside";
  console.log(message);  // inside
}
console.log(message);    // outside

The 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

javascript
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 (price and Price are different)
  • Keywords like let, if or return cannot 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;

Learn JavaScript with a teacher

Join the Web Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp