This tutorial is part of a web programming course for people who have no programming experience.
In programming languages, variables are used to store information. When we create a variable, we give it a name, and then we assign a value for it to hold. Let's assume that we want to create a variable that holds the age of someone, we could do it like so:
var age = 10;
Before moving on, I want to show you a 'command' that will come in handy throughout this course. If you want to display the contents of a variable in the browser, you can use the alert function to show it in a pop up box (we'll talk more about functions in the next lesson):
Variables are extremely powerful because they make programs easy to update. Let's assume you want to show an alert box that displays the user's name in various places throughout your program. You could write your program with this approach (note that the lines beginning with two forward slashes are comments for demonstration purposes, they will be ignored when the code runs in the browser):
alert("Bob"); // a bunch of lines of code might go here alert("Bob"); // maybe a bunch more code might be here alert("Bob");
As you can see, "Bob" is repeated a few times. Let's assume you wanted to change this to "Robert". If these alerts were spread out within many lines of code in your program, then it could be tricky to find all three instances.
Instead of repeating a value in your code, you could use a variable. This is handy because if you decide that you want to change the value, you can just update the line of code that declares the variable. Then all the lines of code that use the variable will be updated to the new value.
var userName = "Bob"; alert(userName); // a bunch of code might go here alert(userName); // maybe a bunch more code might be here alert(userName);
Variables must be declared before they can be initialized, and you can declare a variable without initializing it like this:
Here we've declared a variable, but haven't initialized it by setting it equal to a value. To 'initialize' a variable means to set it to a value (programmers will often say 'assign' a value to a variable as well). You might wonder why you would declare a variable without initializing it, but it's quite common. Many programmers like to declare all their variables together at the top of the code so that you can become familiar with the information the program works with. You can even declare a bunch of variables all in a single line by separating each variable name with a comma:
var age, height, weight;
Later in your program you could initialize a variable by setting it equal to some value like this:
age = 18;
You don't need to include the 'var' keyword if you've already declared the variable.
Sometimes you declare a variable without initializing it because you aren't sure what the value will be. You could let the visitor (user) of a web page page supply the value like this:
var firstName; // some more lines of code might go here firstName = prompt("Please enter your first name."); alert(firstName);
In this example I've used another 'command' that will come in handy throughout the course. The prompt command makes an input box appear so that the user can enter information. The value entered by the use will be stored in a variable (in this case that variable is named 'firstName').
If you declare a variable but never assign a value to it, it will be undefined, which can potentially cause problems if your program expects it to hold a value. If you've ever worked in any other programming language, you may have heard of the word null, which is similar to undefined and means 'no value'.
Variables can be re-assigned, which means that you can change the value stored. This is why they are called variables - they can vary. Consider this code sample:
var age = 7; alert(age); age = 10; alert(age); age = prompt("Enter your age"); alert(age);
In this code sample, I've declared a variable named 'age' and initialized it to a value of 7. Then the value stored is 'alerted' (displayed in an alert box via the alert command). Then the variable is re-assigned to a new value and alerted again. Finally, I used the prompt command to allow the user re-assign a new value to the variable before alerting it one more time.
Variables can store different types of data. You can assign a number to a variable, as we have seen with the 'age' variable above. You can also assign text to a variable, but when you do so, you must remember to add one very important bit of syntax (maybe you noticed it in one of the examples above). Take a look at this example:
var firstName = "Buster";
When you assign text to a variable, you must surround it with quotaion marks. You can use either single, or double quotes, but it must be the same one both sides (for example, if you use double quotes before the text, you must use double quotes after it).
Programmers don't refer to this data type as 'text', instead they'll say string (I assume because it's a string of characters). From this moment forward you will be inundated with the term 'string' when referring to data types, as it is commonly used in every language.
A common mistake among beginners is to forget the quotes when assigning a string to a variable. This will probably cause your program to crash, because without the quotes, the browser will assume that you are referring to another variable name, which probably doesn't exist in your code.
var done = false;
Boolean variables are used all the time in programming because we often want our code to do one thing is something is true, and another thing if something is false.
See if you can you spot the difference between these two variables:
var x = "true"; var y = true;
The first one, x, is storing a string data type, while the second one is storing a boolean. Remember that if a value is enclosed in quotes, then it is a string. Boolean values use the true or false keywords. It may be hard to understand the signicance of different data types now, but it will become more apparent as we get further into the course. You'll be doing yourself a big favor if you pay close attention to the data type that a variable is storing. There are a few other data types that I didn't mention, but we'll be seeing them later.
Expressions are equations that can be solved, such as 5 + 3. This expression evaluates to a value 8 (to 'evaluate' is to solve and equation). We can use expressions to assign values to variables.
var total = 200 + 100; //the variable 'total' holds a value of 300
You'll often see variables used in the expression like this:
var celsius = 40; var fahrenheit = celsius * 9/5 + 32;
You can actually use expressions with strings, not just numbers. If you add two strings together you get a new string:
var str1 = "Hello"; var str2 = "World"; var str3 = str1 + str2;
Weird things can happen if you combine variables of different data types:
var someNumber = 3; var someOtherNumber = "2"; var result = someNumber + someOtherNumber; alert(result);
Because one of the variables was a string, we actually did string concatenation (not math) when we added them together.
Since we are talking about expressions, I want to point out that there is an expression in the last line of this code sample. A variable name all by itself is an expression, and will be evaluated when your program runs. Before the browser executes the alert on the last line, it has to figure out the value stored in the result variable. In this case it will evaluate to a value of "32", which happens to be a string data type.
As I mentioned, it's important to pay attention to the data type of a variable (in other words, the data type of the value being stored by a variable). You can use the typeof keyword to find out the data type of a variable by placing it before the variable name when you use the alert command.
Let's recreate the previous example, but instead of alerting the value of the 'result' variable, let's alert its data type:
var someNumber = 3; var someOtherNumber = "2"; var result = someNumber + someOtherNumber; alert(typeof result);
If you run this code, you'll see 'string' in the alert box, which should tell you that if you add a string variable to a number variable then the result will be a string.
It's important to choose your variable names wisely. If you wanted to create a variable to store the age of a person, you wouldn't name it 'size' because it would be misleading. I once worked with a programmer who like to use variable names like b1, b2, and b3. It wasn't fun trying to figure out how his code worked!
There are some rules for the characters that can be used in variable names. For example, a variable name cannot begin with a number and it cannot contain a space. There are also other rules, but you'll be asked to explore them on your own in an upcoming assignment.
// This will cause an error, because variable names are not allowed to start with numbers var 1stName = "Betty";
When you are writing programs, it's often helpful to print out the value of a variable. You can do this by using the console.log() command. For example, you can 'log' the value that a variable is storing like this:
var lastName = "Jones"; console.log(lastName);
Notice that you put the variable name inside of the parenthesis of the command. I demonstrated how to use the console in the video, but I'll summarize it here. To see the results of using console.log() in your code, press the F12 key while viewing the page in your browser. This will open the Web Developer Tools window. This window is full of indespensible tools for web developers, and we'll be using it a lot in this course. No matter which browser you use (Chrome, Edge, FireFox) pressing F12 will open the web developer tools window. The window may look a little different, depending on which browser you use, but they all have the same basic features. I use Chrome in my classes, and I encourage my students to use Chrome as well. If you are using Chrome and you don't see the error message in the log, you may have to click on the 'errors' icon on the left side, then you should see the error message.