JavaScript Tutorial #1 - Variables

JavaScript Tutorial #1 - Variables


Contents

  1. What is a Variable?
  2. Creating a Variable
  3. Using a Variable
  4. Variable Quiz
  5. Further Reading

1. What is a Variable?

Variables are the building blocks of JavaScript. Without them, your code editor would be a much wordier and much more complicated place.

A variable stores information, and this information is referred to as a 'value'. The value may be, for example, a number, a string, or a boolean (more about these later).

Here is an example of a JavaScript variable:

var age = 30;

2. Creating a Variable

So, how do we create, or 'declare', a variable?

Well, first we need to use the var keyword in order to tell JavaScript that we are about to declare a new variable. JavaScript is a case-sensitive language, so take care not to use uppercase characters (such as Var or VAR).

We immediately follow this up by writing our new variable name, known as the 'identifier'. In the example below, we have called our new variable age.

var age = 30;

You can call your new variable anything, but there are a few rules to keep in mind:

  • It can include letters, numbers, underscores (_), and dollar signs ($).

  • It must start with a letter, an underscore (_), or a dollar sign ($), but not a number!

  • It must not contain any spaces.

There are also a number of reserved JavaScript 'keywords' that cannot be used to name variables. var is one example of a JavaScript keyword, so you cannot use it to name your variable, as in the example below:

var var = 30;

It goes without saying that variable names are there to make life easier. So take care to name variables appropriately:

// Bad Examples:
var variable1 = 30;
var variable2 = 'Dan';

// Good Examples:
var age = 30;
var name = 'Dan';

As we cannot use spaces when naming JavaScript variables, they can get difficult to read. There are a number of different naming conventions, but it is common practice to use camelCase, in which the first letter of every new word (except the first) is capitalised:

// camelCase:
var myFavouriteAnimal = 'Dogs';

Having declared a variable (var) with a valid identifier (such as age), we next need to insert an equals sign (=), known as the 'assignment operator'.

Finally, it's time to add a value to our variable. This may be, for example, a number, a string (text), or a boolean (a true or false value):

  • Number: var age = 30;
  • String: var name = 'Dan'; *Must be in single or double quotation marks.
  • Boolean: var hasChildren = false;

In JavaScript, a semicolon (;) is used to separate different statements (such as the declaration of a variable), though they are not always needed if the statement is separated by a line break. Personally, I always use them just to make sure.

NOTE: As of 2015, JavaScript (ES2015, or ES6) has two additional types of variables, let and const. Both of these are now preferred to var, and we will come back to these in the future when we consider local and global scope. var, let and const all have different uses, but for now we will stick with var.


3. Using a Variable

Having created a variable, we now have a value that is easy to access. We could, for example, have the console return this value by using console.log():

var age = 30;

console.log(age);

NOTE: To open the console in your browser, right click and select 'inspect', then navigate to 'console'.

Console.png

A JavaScript var variable can have it's value reassigned at any time, as in the following example:

var name = 'Dan';
name = 'John';

console.log(name);

Here, the console would return the string value John. Notice how we did not have to redeclare the variable by using the var keyword, as the variable with the identifier name has already been declared.

JavaScript can perform arithmetic by using operators such as + or -. For this, we can use literal values, in which the value is not assigned to a variable, as in console.log(3 + 2);. We can also use variables that contain values:

var numberOfCats = 3;
var numberOfDogs = 2;
var numberOfPets = numberOfCats + numberOfDogs;

console.log(numberOfPets);

You can also use a combination of literals and variables, as in the following example:

var numberOfCats = 3;
var numberOfPets = numberOfCats + 2;

console.log(numberOfPets);

We can also use the + operator with strings (text). In these cases, JavaScript will link, or concatenate, the various strings together, as in the following examples:

console.log('John ' + 'Smith');

var firstName = 'John';
var secondName = 'Smith';
var fullName = firstName + ' ' + secondName;

console.log(fullName);

In both of these examples, John Smith would be returned to the console. Note that, as there are no spaces in the variables, it is necessary to add a space as a separate string (' ') when concatenating.


4. Variable Quiz

1 - Which of the following is NOT a valid JavaScript variable name, or 'identifier'?

a) var age = 30; b) var myage = 30; c) var age1 = 30; d) var 1age = 30;


2 - Which of the following variables contains a number value?

a) var name = 'Dan'; b) var age = 30; c) var rank = '3'; d) var wonRace = false;


3 - What would the following return to the console?

var birthYear = 1991;
var currentYear = 2021;

console.log('I am ' + (currentYear - birthYear) + ' years old.');

4 - What is the value of the variable booksRead?

var booksRead = 5;
booksRead = 7;
booksRead = 10;

5 - What is the value of the variable age?

var birthYear = 1981;
var currentYear = 2021;
var age = currentYear - birthYear;

ANSWERS

  1. var 1age = 30;(d) is NOT a valid JavaScript variable name, or 'identifier', because it starts with a number. All of the others are valid. In the case of var myage = 30;(b), it is more common to use camelCase: var myAge = 30;.

  2. var age = 30;(b) contains a number value. Though var rank = '3'(c) appears to contain a number, the single quotes define it as a string. In this case, JavaScript will treat this value as text, not a number.

  3. The console would return I am 30 years old. Used with two or more strings (text), the + symbol will link, or concatenate, the various strings.

  4. The value of the variable booksRead is 10. The value of a JavaScript variable can be reassigned time and time again (unless it is a const variable!), and so the most recent reassignment here was the value 10.

  5. The value of the variable age is 40, as JavaScript will calculate currentYear, which has a value of 2021, - birthYear, which has a value of 1981.


5. Further Reading

Thank you very much for reading! If you would like to read about JavaScript variables in more detail, you can check out the following websites: