A variable is a container for a value, like a number we might use in a sum, or a string that we might use as part of a sentence. But one special thing about variables is that their contained values can change. Let’s look at a simple example:
<button>Press me</button> const button = document.querySelector('button'); button.onclick = function() { let name = prompt('What is your name?'); alert('Hello ' + name + ', nice to see you!'); }
In this example pressing the button runs a couple of lines of code. The first line pops a box up on the screen that asks the reader to enter their name, and then stores the value in a variable. The second line displays a welcome message that includes their name, taken from the variable value.
Variables just make sense, and as you learn more about JavaScript they will start to become second nature.
Another special thing about variables is that they can contain just about anything — not just strings and numbers. Variables can also contain complex data and even entire functions to do amazing things. You’ll learn more about this as you go along.
Note: We say variables contain values. This is an important distinction to make. Variables aren’t the values themselves; they are containers for values. You can think of them being like little cardboard boxes that you can store things in.
To use a variable, you’ve first got to create it — more accurately, we call this declaring the variable. To do this, we type the keyword var
or let
followed by the name you want to call your variable:
let myName; let myAge;
Here we’re creating two variables called myName
and myAge
. Try typing these lines into your web browser’s console. After that, try creating a variable (or two) with your own name choices.
Note: In JavaScript, all code instructions should end with a semi-colon (;
) — your code may work correctly for single lines, but probably won’t when you are writing multiple lines of code together. Try to get into the habit of including it.
You can test whether these values now exist in the execution environment by typing just the variable’s name, e.g.
myName; myAge;
They currently have no value; they are empty containers. When you enter the variable names, you should get a value of undefined
returned. If they don’t exist, you’ll get an error message — try typing in
scoobyDoo;
Note: Don’t confuse a variable that exists but has no defined value with a variable that doesn’t exist at all — they are very different things. In the box analogy you saw above, not existing would mean there’s no box (variable) for a value to go in. No value defined would mean that there IS a box, but it has no value inside it.
Once you’ve declared a variable, you can initialize it with a value. You do this by typing the variable name, followed by an equals sign (=
), followed by the value you want to give it. For example:
myName = 'Chris'; myAge = 37;
Try going back to the console now and typing in these lines. You should see the value you’ve assigned to the variable returned in the console to confirm it, in each case. Again, you can return your variable values by simply typing their name into the console — try these again:
myName; myAge;
You can declare and initialize a variable at the same time, like this:
let myDog = 'Rover';
This is probably what you’ll do most of the time, as it is quicker than doing the two actions on two separate lines.
Once a variable has been initialized with a value, you can change (or update) that value by simply giving it a different value. Try entering the following lines into your console:
myName = 'Bob'; myAge = 40;
You can call a variable pretty much anything you like, but there are limitations. Generally, you should stick to just using Latin characters (0-9, a-z, A-Z) and the underscore character.
myage
is a different variable from myAge
.var
, function
, let
, and for
as variable names. Browsers recognize them as different code items, and so you’ll get errors.Note: You can find a fairly complete list of reserved keywords to avoid at Lexical grammar — keywords.
Good name examples:
age myAge init initialColor finalOutputValue audio1 audio2
Bad name examples:
1 a _12 myage MYAGE var Document skjfndskjfnbdskjfb thisisareallylongstupidvariablenameman
Try creating a few more variables now, with the above guidance in mind.
There are a few different types of data we can store in variables. In this section we’ll describe these in brief, then in future articles, you’ll learn about them in more detail.
So far we’ve looked at the first two, but there are others.
You can store numbers in variables, either whole numbers like 30 (also called integers) or decimal numbers like 2.456 (also called floats or floating point numbers). You don’t need to declare variable types in JavaScript, unlike some other programming languages. When you give a variable a number value, you don’t include quotes:
let myAge = 17;
Strings are pieces of text. When you give a variable a string value, you need to wrap it in single or double quote marks; otherwise, JavaScript tries to interpret it as another variable name.
let dolphinGoodbye = 'So long and thanks for all the fish';
Booleans are true/false values — they can have two values, true
or false
. These are generally used to test a condition, after which code is run as appropriate. So for example, a simple case would be:
let iAmAlive = true;
Whereas in reality it would be used more like this:
let test = 6 < 3;
This is using the “less than” operator (<
) to test whether 6 is less than 3. As you might expect, it returns false
, because 6 is not less than 3! You will learn a lot more about such operators later on in the course.
An array is a single object that contains multiple values enclosed in square brackets and separated by commas. Try entering the following lines into your console:
let myNameArray = ['Chris', 'Bob', 'Jim']; let myNumberArray = [10, 15, 40];
Once these arrays are defined, you can access each value by their location within the array. Try these lines:
myNameArray[0]; // should return 'Chris' myNumberArray[2]; // should return 40
The square brackets specify an index value corresponding to the position of the value you want returned. You might have noticed that arrays in JavaScript are zero-indexed: the first element is at index 0.
In programming, an object is a structure of code that models a real-life object. You can have a simple object that represents a box and contains information about its width, length, and height, or you could have an object that represents a person, and contains data about their name, height, weight, what language they speak, how to say hello to them, and more.
Try entering the following line into your console:
let dog = { name : 'Spot', breed : 'Dalmatian' };
To retrieve the information stored in the object, you can use the following syntax:
dog.name
JavaScript is a “dynamically typed language”, which means that, unlike some other languages, you don’t need to specify what data type a variable will contain (numbers, strings, arrays, etc).
For example, if you declare a variable and give it a value enclosed in quotes, the browser treats the variable as a string:
let myString = 'Hello';
Even if the value contains numbers, it is still a string, so be careful:
let myNumber = '500'; // oops, this is still a string typeof myNumber; myNumber = 500; // much better — now this is a number typeof myNumber;
Try entering the four lines above into your console one by one, and see what the results are. You’ll notice that we are using a special operator called typeof — this returns the data type of the variable you type after it. The first time it is called, it should return
string
, as at that point the myNumber
variable contains a string, '500'
. Have a look and see what it returns the second time you call it.
Many programming languages have the concept of a constant — a value that once declared can’t be changed. There are many reasons why you’d want to do this, from security (if a third party script changed such values it could cause problems) to debugging and code comprehension (it is harder to accidentally change values that shouldn’t be changed and mess things up).
In the early days of JavaScript, constants didn’t exist. In modern JavaScript, we have the keyword const
, which lets us store values that can never be changed:
const daysInWeek = 7; const hoursInDay = 24;
const daysInWeek = 7; daysInWeek = 8;
In this task we want you to:
myName
.myName
with a suitable value, on a separate line (you can use your actual name, or something else).myAge
and initialize it with a value, on the same line.Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
In this task you need to add a new line to correct the value stored in the existing myName
variable to your own name.
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
The final task for now — in this case you are provided with some existing code, which has two errors present in it. The results panel should be outputting the name Chris
, and a statement about how old Chris will be in 20 years’ time. How can you fix the problem and correct the output?
Try updating the live code below to recreate the finished example:
Download the starting point for this task to work in your own editor or in an online editor.
By now you should know a reasonable amount about JavaScript variables and how to create them. In the next article, we’ll focus on numbers in more detail, looking at how to do basic math in JavaScript.