Chapter 3: Javascript Variables and Data Types

3.1 What are variables?

Javascript variablesVariables are names given to data that we need to store and manipulate in our programs. For instance, suppose your Javascript program needs to store the age of a user. To do that, we can name this data userAge and declare the variable userAge using the following statement.

var userAge;

In the statement above, var stands for variable and is a reserved keyword in Javascript. Whenever we declare a variable, we should always use the var keyword to let the browser know that we are declaring a variable. In addition, we end the statement with a semi-colon. All statements in Javascript must end with a semi-colon.

After you declare the variable userAge, you can access and modify this data by referring to it by its name.

For instance, you can give this variable a value. This is known as assigning a value to the variable. To do that, you write

userAge = 23;

Now, the value of userAge becomes 23. We can change this value in our program later.

In addition to declaring a variable and assigning a value to it in two separate statements, you can combine the two statements into a single statement as shown below:

var userAge = 23;

You can also choose to declare multiple variables in one go. To do that simply write

var userAge = 30, userName = 'Peter';

This is equivalent to

var userAge = 30;
var userName = 'Peter';

To get a feel for how variables work, create a new file in Brackets and save it as chap3.js. Change the <script> tag in template.html to link to chap3.js.

Now, add the following lines to chap3.js.

//Declaring userAge
var userAge = 23;
console.log(userAge);

//Updating userAge
userAge = 33;
console.log(userAge);

In the examples above, we declared the variable userAge, assigned the values 23 and 33 to it, and displayed the values after each assignment.

Save the two files (template.html and chap3.js) and refresh template.html in your browser. You’ll get the following output in the console:

23
33

Note that we do not enclose the variable name userAge with quotation marks when using the console.log() method in the examples above. If we write

console.log("userAge");

we’ll get

userAge

as the output instead because Javascript treats "userAge" as a text message instead of a variable name.