Suppose you want to show a student’s name, age and city on a website. Where will you keep these values? We use variables. Let’s understand them with small examples, then display the values on a web page.

This is Class 2 of our JavaScript lessons. If you are new, first read What is JavaScript? Then come back and type the examples yourself. Do not just read the code. Change a value, run it and check the result.

What is a variable?

A variable is a name used to hold a value in your program. The name is called an identifier. The value may be a number, some text, a true-or-false value or other data.

let age = 25;
console.log(age);

age = 26;
console.log(age);

The output is 25, followed by 26. First we stored 25 in age. Then we changed it to 26. We use let only when declaring it; we do not write let age again when updating the same variable.

The = sign assigns a value. Read age = 26 as “store 26 in age.” It is not a question asking whether the two sides are equal.

var, let and const

You will see three keywords for declaring variables. For new practice, start with const when you will not reassign the variable, and let when you will.

KeywordSimple meaningExample
letUse it when you need to assign another value later.let age = 25;
constGive it a value now. You cannot reassign it later.const PI = 3.14159;
varAn older declaration you will still find in existing code.var quantity = 15;

let and const are block-scoped. A block is a section inside braces, such as the body of an if statement. var is not block-scoped; inside a function, it is scoped to that function. We will practise scope separately.

const student = { name: "John" };
student.name = "Jane";

console.log(student.name);

This prints Jane. A useful point: const stops you from reassigning the variable. It does not freeze the object stored in it. Here we changed a property of the same object.

Rules for valid variable names

For beginner examples, use English letters, digits, underscores and dollar signs. Start with a letter, _ or $. A digit can come after the first character. JavaScript also supports many Unicode letters, but simple names are easier to practise with.

  • Do not put spaces in a name.
  • Do not start a name with a digit.
  • Do not use symbols such as % or & in the name.
  • Avoid reserved words such as var, const and for.
  • Remember that names are case-sensitive.
NameValid?Reason
A1, A_1, _A1YesThese follow the naming rules.
77ANoStarts with a digit.
first nameNoContains a space.
A%2, A&2NoContains an invalid symbol.
varNoA reserved keyword.
VarYesDifferent from lowercase var, but not a helpful name.
const age = 25;
const Age = 30;

console.log(age);
console.log(Age);

The output is 25 and 30. These are two different names. In your own code, use clear names such as studentAge instead of creating names that differ only by one capital letter.

Camel case notation

In camelCase, the first word starts with a small letter. Each next word starts with a capital letter. We join the words without spaces.

const firstName = "John";
const lastName = "Doe";
const phoneNumber = "+92 300 1234567";
const addressLine1 = "123 Main Street";
const isStudent = true;
const numberOfSiblings = 2;
const hasCar = false;

Look at phoneNumber. The p is small and the N is capital. This is the usual style for JavaScript variables and ordinary functions. Choose a name that tells you what the value means.

Pascal case notation

In PascalCase, every word starts with a capital letter, including the first word.

const FirstName = "John";
const LastName = "Doe";
const PhoneNumber = "+92 300 1234567";
const IsStudent = true;

These are valid variable names. The difference is the writing style. For ordinary variables, prefer camelCase. PascalCase is commonly used for class names and React component names, such as StudentProfile. It does not change the value or make the variable a different data type.

Expression evaluation: numbers and text

Now look carefully at quotation marks. 20 is a number. "20" is a string containing two characters. The + operator can add numbers or join text, so the result depends on the values.

ExpressionResultWhat happens?
20 + 323Adds two numbers.
"20" + 3"203"Joins the values as text.
"20" - 317Converts this numeric string for subtraction.
"20" * 360Converts it for multiplication.
"20" / 36.666666666666667Divides; it does not round to 7.

If you want addition, convert text to a number clearly:

const enteredValue = "20";
const total = Number(enteredValue) + 3;

console.log(total);

The output is 23. Do not depend on automatic conversion without understanding it. For a form, also check that the entered value is suitable before using it.

What if we do not give a value?

let carBrand;
console.log(carBrand);

This prints undefined. We declared the variable but did not assign a value yet. Later, we can write carBrand = "Toyota";. With const, you must provide the starting value in the declaration.

Show variables on a page with the DOM

The DOM is the browser’s representation of your HTML page. JavaScript can use it to find an element, change its text or add a new element.

Make a file called age.html. Write this code and open the file in your browser:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Show a variable</title>
</head>
<body>
    <div id="age-output"></div>

    <script>
        const age = 25;
        const output = document.querySelector("#age-output");
        output.textContent = "Age: " + age;
    </script>
</body>
</html>

You will see Age: 25. We used the existing div. To create a new element instead, use document.createElement("div"), set its text and append it to the page. For plain text, textContent is a good choice because it does not interpret the value as HTML.

Display several variables in one table

Let’s put the values together. Create two files in the same folder: variables.html and script.js.

1. Write the HTML

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Variables table</title>
</head>
<body>
    <h1>Student variables</h1>
    <table id="variableTable">
        <thead>
            <tr>
                <th>Variable name</th>
                <th>Value</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

    <script src="script.js"></script>
</body>
</html>

2. Write the JavaScript

const variables = [
    { name: "age", value: 25 },
    { name: "firstName", value: "John" },
    { name: "isStudent", value: true },
    { name: "city", value: "Rawalpindi" },
    { name: "hobbies", value: "reading, painting, swimming" }
];

function displayVariables() {
    const tableBody = document.querySelector("#variableTable tbody");
    tableBody.textContent = "";

    variables.forEach(function (variable) {
        const row = document.createElement("tr");
        const nameCell = document.createElement("td");
        const valueCell = document.createElement("td");

        nameCell.textContent = variable.name;
        valueCell.textContent = variable.value;

        row.appendChild(nameCell);
        row.appendChild(valueCell);
        tableBody.appendChild(row);
    });
}

displayVariables();

Now open variables.html. The table shows five rows. We created each row with JavaScript and placed the name and value in separate cells. Clearing the table body first means calling the function again will not add duplicate rows.

Try changing the values here

This practice example uses the same idea. Change the name and age, then press “Show values.” It only updates this page; the values are not sent or saved.

Variable nameValue
Your output will appear here.

Ready to practise.

Practise it yourself

  1. Write five valid names and five invalid names. Explain each answer.
  2. Write favoriteColor, phoneNumber and numberOfSiblings in PascalCase.
  3. Predict the result of "10" + 5 and Number("10") + 5, then run them.
  4. Add a row for quantity with the value 10 + 5.
  5. Create a hobbies array and use hobbies.join(", ") to display it as readable text.

Keep your code on separate lines. Give each variable a clear name. When the output is different from your prediction, check the spelling, capital letters, quotation marks and the value’s type.

Further reading

Once variables feel familiar, explore our JavaScript course. Continue to React development for interfaces or the MERN stack course for Node.js and APIs.

TURN READING INTO PRACTICE

Give your first idea a try.

Explore the JavaScript course outline, or sign in to practise with your active course enrollment.

← Back to all blogs