Variables

Introduction

Variables are how a programming language stores information in a computer’s memory. We can think of them as containers for data. Once data is stored there, we can act on and use this data in other parts of our program.

Variables sitting in the computer’s RAM - Random Access Memory

variable containers

We are going to look at these types of data that JavaScript variables can store:

  • undefined
  • string
  • number
  • boolean

Declaring variables

Before we can use variables, we need todeclare (create) them.

Variables are declared or created using the let and const keywords. Variables do not ‘hold’ values, but they ‘point’ to them. We need to work with values when we handle user interaction, for example, when we save their credentials while they register for an account on social media.

javascript
	let pet;
	const passportNumber;

Above, we’ve created a variable called pet. We haven’t given pet a value, so at the present moment it is empty or undefined in that it does not point to a value. If you log pet to the browser console, it will return a value of undefined.

Giving a variable a value when you declare it is called initialising or assigning the variable.

It is important to know which type of variable to use for the purposes of our code. We use let for variables that we wish to update at some point or another, just like a lunchbox where we can replace the old contents with new lunch inside for a new day. We use const for variables that we wish to keep the same throughout our code.

Here is an example of a variable declared using const:

javascript
	const passportNumber = 1122334455;

Here is an example of a variable declared using let:

javascript
	let pet;
	pet = "cat";
	pet = "dog";

The code above first declares pet as a let variable, then on the next line it is initialised (officially created) to point to the value of “cat”. On the third line we can update it to point to the value of “dog”. If we tried to do the same thing using a const variable, JavaScript will throw a type error that reads “invalid assignment to const”.


The video below is an introduction to variables:

Watch on Vimeo

undefined vs the is not defined error

This video looks at the difference between the (valid) value undefined and the error is not defined.

Watch on Vimeo

Strings

Strings are pieces of text. They can range in size from one character like a to a whole book of characters.

They’re enclosed in either single ' or double quotes. At Noroff, we use double quotes for our string variables.

Let’s create our first string variable.

Variable names must start with a lowercase letter (a to z), an uppercase letter (A to Z), and a dollar sign $ or an underscore _. We are only going to use lowercase letters to begin our variable names.

To declare a variable, we use let or const accordingly, the name of our variable and the value if we decide to initialise it.

javascript
	let pet = "dog";

We’ve initialised the pet variable with the string value “dog”. We can say we’ve assigned the value “dog” to pet, and now pet points to the value “dog”.

We can now use that variable in our code:

javascript
	console.log(pet);

We use camelCase to name variables.

Using this method, the first word of a variable name starts with a lowercase letter and subsequent words are joined to the first and begin with an uppercase letter:

javascript
	let loggedIn;
	let orderHasShipped;
	let lastName;

Note that variables names cannot include spaces and need to be as explicit as possible.


Joining strings together

We can join strings together using the + sign, an action called concatenation.

javascript
	let letters = "a" + "b";
	
	console.log(letters);
	// "ab"

Let’s assign those string values to variables and then join them:

javascript
	let letter1 = "a";
	let letter2 = "b";
	
	let letters = letter1 + letter2;
	
	console.log(letters);
	// "ab"

Anything inside quotes (even numbers), is a string, . The variable amount below has a string value.

javascript
	let amount = "7";

In this video, we take a look at string variables.

Watch on Vimeo

Selecting HTML elements with JavaScript

Before we look at adding string variables to an HTML page, we must determine how to select and modify HTML elements using JavaScript’s document.querySelector function.

Watch on Vimeo

Adding string variables to an HTML page

In this video, we will add string variables to HTML elements.

Watch on Vimeo Code from the video

Numbers

Numbers in JavaScript can be both integers (whole numbers) and decimals.

javascript
	let integer = 8;
	let decimal = 7.1;

Basic arithmetic operators

We can use the following operators with numbers in JavaScript.

Operator Name Example
+ addition 3 + 2
- subtraction 7 - 1
* multiplication 6 * 4
/ division 9 / 3
% remainder 5 % 2

If you try to add a number value to a string version of a number like this:

javascript
	7 + "7";

You will end up with 77, not 14.

This is because when one of the values is a string value, the + operator joins both values together as if they were both strings. It doesn’t add them together as it would if all values were number values.

You can convert a string version of a number to a proper number using the parseInt and parseFloat functions.

To convert a number without a decimal point, use parseInt.

javascript
	let integer = "7";
	let convertedInteger = parseInt(integer);
	// 7

To convert a number to a decimal point, use parseFloat.

javascript
	let decimalNumber = "7.9";
	let convertedDecimalNumber = parseFloat(decimalNumber);
	// 7

The remainder operator (sometimes called the modulus operator) returns the remainder of a division operation:

javascript
	let remainder = 5 % 2;
	console.log(remainder);
	// 1
	
	let remainder2 = 4 % 2;
	console.log(remainder2);
	// 0

This video looks at number variables.

Watch on Vimeo Code from the video

Booleans

Boolean values are either true or false.

javascript
	let isLoggedIn = true;
	let onSpecial = false;

Note that there are no quotes around boolean values.

The variable badBoolean below has a string value, so it’s not a boolean.

javascript
	let badBoolean = "true";

The variable properBoolean below has a boolean value.

javascript
	let properBoolean = true;

Checking data types

We can use the typeof operator to check what type of data a variable holds. We can use it with or without brackets.

javascript
	let colour = "red";
	
	typeof colour;
	// "string"
	
	typeof "blue";
	// "string"
	
	typeof 14;
	// "number"
	
	typeof false;
	// "boolean"

We can assign the result of a typeof operation to a variable.

javascript
	let animal = "elephant";
	let typeOfAnimal = typeof animal;
	console.log(typeOfAnimal);
	// string

The video below is an introduction to the typeof operator.

Watch on Vimeo Code from the video

Lesson Task

There are practice questions in the master branch of this repo.

There are example answers in the answers branch.

Try the exercises before checking the solutions.