Introduction to programming
Variables
Now on to the interesting stuff! We'll now have a look at the programming basics that exist in pretty much every programming language, in one form or another. Before starting this section, make a new copy of the template.html file and open it in your browser and text editor.
Variable basics
Variables are containers that allow you to store something that you want to use later on, be that a simple name or age value, or something more complicated. Why would you want to do this? Let's look at a simple program that says hello to you: See my Hello example (don't look at the source code!)
Without variables, it would be impossible to create a personalised hello message. You'd just have to stick to "Hello there.", which would be really boring. So variables are all about allowing us to create programs that dynamically change depending on things that differ as the program is being used, such as the user using the program, the date and time of day, the weather, and so on. Programming is pretty much impossible without variables.
To use a variable, we first have to declare it — we say "I am making this variable exist. Its name is x, and its initial value is y."
A really simple code example:
var myHairColor = "brown";
// Note the quotes; these can be single or double quotes;
//your choice, as long as you are consistent
You could also then change a variable later on, once it is declared.
var myHairColor = "brown";
// declare a variable myHairColor, with an initial value of "brown"
myHairColor = "red";
// change the existing variable myHairColor's value to "red"
A few more simple examples follow:
var myName = "Chris";
// A string
// Also note that JavaScript is case sensitive, so myname is
// a different variable to myName
var myAge = 35; // a number
var haveKids = true; // a boolean
var favouriteThings = ['raindrops','kettles','packages','ponies'] // an array
Exercise: Proving how variables exist and are stored
As a quick exercise, let's go into the browser developer console and try accessing a new variable the console pane (the console is basically a way to access the internal state of the code or application). To open the console, press Ctrl + Shift + I; Cmd + Opt + I on Mac OSX; F12 on Internet Explorer, and click the console tab.
To call or access a variable, you just use the variable name. Enter this into the console:
myCar
This should give you a result of undefined
, because the variable doesn't yet exist.
Let's try declaring the variable: type the following into the console:
var myCar = "Citroen";
and then trying this again in the console:
myCar
The console should now return the variable's value to you.
When we have a value stored in a variable, we can use it in our program by simply saying the variable name again. Let's look at something slightly more complex that actually does something interesting. The prompt function opens up a dialog box asking the user to enter a value into a text box. When they have done so, it stores that value in a variable:
var myHairColor = prompt("Enter your hair color");
// Ask the user for their hair color
You can then choose to do something else with that value:
alert("Chris has " + myHairColor + " hair.");
// display a personalised message about hair colour
alert
is a simple function that pings up a dialog box containing whatever message you include inside it, in this case Chris has " + myHairColor + " hair."
.
This string of text may look strange, and we'll explain it better later on. For now, let's just say that we are gluing together three things:
- The text
"Chris has "
- The current value inside the
myHairColor
variable - The text
" hair."
A lot of programming involves gluing different things together to get the output you want.
Exercise: write the hello example from before
The hello example that we checked out at the very start of this section is very similar in the way that it works to the hair colour example we just studied. I'd like you to try writing the hello example into your working template file, and then run it to get it working. DON'T look at the source code unless you get stuck!
Variable types
In JavaScript, different variables have different assigned types:
- Strings contain strings of text. The presence of quote marks makes them a string. If you didn't use quote marks, you would get an error, because the browser would think the variable value was not a string, but another variable name instead.
- Integers contain numbers, which don't need quote marks.
- Booleans contain true/false values. These are very useful when creating program logic, as you'll see later.
- Arrays contain multiple values at once; these are very useful for containing multiple related values that you want to manipulate in a similar way.
Exercise: finding the types of variables
Let's see if I'm telling the truth. In the JavaScript section of your template file, enter the following block of code, then save, then refresh the browser:
var myHairColor = "brown";
// This is a string
var myAge = 35;
// This is an integer
var haveKids = true;
// This is a boolean
var faveFoods = ["Coco Pops", "Fajitas", "Curry", "Bacon"];
// This is an array
Then in the browser console, try outputting the type of each variable, using the typeof
operator, like this:
typeof myHairColor;
// Return the variable type of the myHairColor variable
What do you get when you try this on an array?
An aside on JavaScript syntax
Before we go much further, we ought to dwell on some simple but important syntax rules. A slightly more complex example might look like so:
var squareArea = function(w,h) {
// This is a function stored in a variable;
//we'll look at these more later
var result = w * h;
// Here we are multiplying the w and h arguments together and
//storing them in a variable called result
alert(result);
// Now we are printing the result variable into a dialog box
// on the screen.
};
- The
var
keyword is used to declare a variable; make it exist in the first place. - The next bit is the variable name, which can be almost anything of your choosing, but with a few restrictions. You can't use numbers at the start, and you can't use spaces, punctuation or reserved characters anywhere. You are also advised to use easy to remember, simple names, not too long and not too short. Above I've used lower camel case, first word lower case, and subsequent words capitalised and joined onto the end. This makes your variables easy to read and not too complex to type.
- The next bit is an equals sign, which means "we are making the bit of the left equal to the bit of the right." In this case we are making
squareArea
equal a function that multiplies two numbers together. This is also called the assignment operator; more on operators below. - The final bit of the variable is whatever you want to store inside the variable — in this case an entire function.
The curly braces — { … }
— are very important in JavaScript. These signify the start and end of a block of code that is all related, and is run together according to a set condition or action (e.g. when a user presses a button, or when a variable holds a certain value.) For each open curly brace, there MUST be a closed curly brace, otherwise the program won't work.
The semi colons (;
) are also important. These signify the end of one instruction and where another one starts. Without these, the program probably won't work as expected
Also note that whitespace doesn't matter much to JavaScript, except inside strings and as a separator for values, keywords, etc. All the whitespace in your code is basically just there to make the code more readable. So
var myName;
var yourName;
Is equivalent to
var MyName;var yourName;
Operators
In programming you'll meet many operators that you can use for calculations and comparisons. We've already seen a couple, such as =
and typeof
, and I've provided a more complete list of JavaScript's common operators below for reference. We won't laboriously go through all of these, just a few to give you an idea. We'll see examples of others as we move through the course.
- + : the concatenation or addition operator, depending on what it is used on
- * : the multiplication operator
- / : the division operator
- - : the subtraction operator
- % : the modulus operator; returns the remainder of one number being divided by another
- = : the assignment operator
- == : the equality operator (don't use this)
- ===: the strict equality operator (use this instead)
- || : the or operator
- && : the and operator
- ! : the not operator
Exercise: making use of JavaScript operators
Let's play with a few operators. Try putting each of the below lines into the browser console to see what happens:
var myHairColor = "brown";
"My hair color is " + myHairColor;
// Join together the string specified in this line, and the one stored in myHairColor
var myAge = 34;
myAge + 26;
// Add together two numbers
var num1 = "34";
var num2 = "26";
num1 + num2;
// Add together two strings?
What did the third code block give you? Not what you expected? Why is this?
Note: you can change the variable type of your variables with various built in JavaScript functions, for example keep num1 and num2 as strings above, and try the following.
Number(num1) + Number(num2);
Let's try some other examples, e.g.
8 % 2;
8 + 4 / 3 * 4;
The last example is interesting - does it give you the result you were expecting? (I would expect the result to be 1!) JS uses operator precedence to dictate what order the different parts of the equation will be executed in. If it is not turning out like you'd hoped, you can always add brackets to force the order, for example:
(8 + 4) / (3 * 4);
This work is licensed under a Creative Commons Attribution 4.0 International License. Share it, make it better, use it for good.