Variables and Data Types

This lesson is part of the Web Programming 1 Course.

We're going to dive into the nuts and bolts of the JavaScript programming language in this lesson. It's a little bit tedious, and it may feel a bit overwhelming. But hang in there, because it's important, and because everything that we discuss in this lesson will be re-enforced in all the lessons that come after it.

It's important that you follow along with the video, and type the code along with me. This is how you'll get to be good at writing code.

You should be using Chrome as your browser. You could use another browser if you want, but I use Chrome and it will help if we are all using the some one.

Go ahead and create a new web page called variables-and-data-types.html in your JavaScript folder and then add a script element. We'll put all of our JavaScript code for this lesson inside the script element.

Variables

In programming languages, variables are used to store information. They are a fundamental building block of any programming language (not just JavaScript).

Declaring and Initializing Variables

When we create a variable, we give it a name, and then we can 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:

let age = 10;

There's a lot we can talk about in this one line of code! Let's start with the syntax:

  1. When you declare (create) a variable, you start the line with let.
  2. After let, you enter the name of the variable that you are creating. You get to come up with your own names, but there are some rules to how you can name them. (we've named this one 'age' because it will store a person's age).
  3. Then comes an equals sign followed by the initial value that the variable will store. So, in this single line of code, we declare a variable named 'age', and initialize it to a value of 10.

Declaring and initializing variables is a fundamental task in any programming language.

The line of code above is a statement. For now you can think of a statement as a single line, or command, in your program. But you'll soon see that this is not always true.

Traditionally, statements in JavaScript should end with a semi-colon, but there's usually no problem if you omit it. But in this course I'll encourage to include the semi-colons so that you get used to them. Some languages, such as Java and C#, require a statement to end with a semi-colon, so it's a good habit to get into.

You can declare a variable without initializing it, like so:

let age;

It may seem strange to declare a variable without initializing it, but it's actually quite common. Many programmers like to declare variables at the top of a file and initialize them later in the code. This allows you to see that variables that will be used throughout the file at the very top.

You could actually declare a bunch of variable all in a single statement, like so:

let age, height, weight;

Note the syntax, each variable name is separated by a comma.

The long way to do this would be to declare each variable separately, with it's own statement:

let age;
let height;
let weight;

You'll quickly find out that there are different ways to accomplish the same thing in your code, which can be confusing for beginners. You'll also learn that programmers love short-cuts!

The let Keyword

A bit more about let - it is a keyword in JavaScript. Every language has a set of words that have special meaning, and in JavaScript let means that we are declaring a variable that may change later in the program.

To demonstrate this, let's update our program to look like this:

let age = 10;
console.log(age);
age = 11;
console.log(age);

This program is useless, except that it shows you can change the initial value of a variable (as long as it was declared with let).

On the third line, a new value (11) is assigned to the age variable. Note that this line does NOT include let. You only use let once for a variable, only when you declare it. If you try to declare the same variable more than once, your program will crash:

let age = 7;
let age = 8; //CRASH!!! - age has already been declared

The const keyword

There is another keyword that you can use to declare variables, and it will prevent their value from being changed.

const votingAge = 18;

If you use const to declare a variable, then you cannot change it's value later in the program ('const' is short for 'constant' which implies that it is unchanging).

const votingAge = 18;
votingAge = 21; // CRASH! - You cannot change the value of a constant

There are many cases when you do not want a variable's value to be changed, because it could lead to bugs in your program, so you should use const to declare them. That way, if you accidentally do change them, your program will crash immediately and you will be aware of the problem.

Now is a good time to show the console log in the web developer tools, and what it looks like when an app crashes.

By the way, if you aren't sure whether to use let or const when declaring a variable, I suggest you lean toward const. If you find out later that you do need to change the value, you could go back and change the declaration to use let.

The var Keyword

The let and const keywords were not always a part of the JavaScript language. Before that, in the old days, we used the var keyword to declare all variables. I'm only mentioning this because you'll still see var all over the place if you look at JavaScript code on the internet. But nowadays, you should use let or const instead.

JavaScript is Case Sensitive

JavaScript keywords are case-sensitive, so make sure you enter let and const with all lowercase letters.

Variable names in JavaScript are also case-sensitive, so be aware that this code is not correct:

const score = 99;
console.log(Score); // WRONG! should be score, not Score

Data Types

Variables can store different types of data. You can assign a number to a variable, as we have seen with the 'age' variable above.

let age = 10; // the data type is number

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:

const name = "Buster"; // The data type is string

When you assign text to a variable, you must surround it with quotation 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.

const day = wednesday;
// Since there are no quotes around wednesday, 
// JavaScript assumes it is supposed to be a variable named wednesday
// If you have not declared a variable named wednesday, the program will crash

// here is the proper way to do it...
const day = "wednesday";

Another data type that we'll be using a lot in this course is called boolean. If you remember from the HTML part of the course, a boolean value can be either true or false. true and false are keywords in JavaScript and they are used to assign values to variables that are meant to hold booleans. Here's how you can declare and initialize a boolean variable:

let done = false; //The data type is boolean

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.

Can you spot the difference between the variables on these two lines of code?:

let x = "true"; // the data type is string
let y = true;   // the data type is boolean

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 significance 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. But for now, we'll just use strings, numbers, and booleans.

let firstName = "Buster"; // the value is Buster, the data type is string
let highScore = 98;       // the value is 98, the data type is number
let lowScore = "55";	  // the value is 55, the data type is string!!!
let likesPizza = true;    // the value is true, the data type is boolean

camelCase

Notice how I named the variables firstName, highScore, and likesPizza. You cannot put spaces in your variable names, so instead we use an approach known as camelCase, which requires you to start all of your variable names with a lowercase letter, and use a capital letter (instead of a space) when there's a new word.

Remember that you, as a programmer, get to come up with your own variable names. But good programmers will use names that describe the data that the variable is storing.

Expressions

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.

let total = 200 + 100;
//the variable 'total' holds a value of 300

You'll often see variables used in the expression like this:

let celsius = 40;
let 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:

const str1 = "Hello";
const str2 = "World";

const str3 = str1 + str2;

Adding strings together like this is known as string concatenation. We'll be doing a lot of string concatenation in this course. Working with strings is a huge part of programming, and we'll soon see that there are lots of ways to manipulate strings in JavaScript.

Weird things can happen if you combine variables of different data types:

let someNumber = 3;  
let someOtherNumber = "2";
let result = someNumber + someOtherNumber;
console.log(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 update the previous example, by displaying the data type of the result variable:

var someNumber = 3;  
var someOtherNumber = "2";
var result = someNumber + someOtherNumber;
console.log(result);
console.log(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.

Naming Variables

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
let 1stName = "Betty";

Good programmers use camelCase when they name variables in JavaScript. I will be using camel case for my variable names in this course, and you should do a quick search of the net for a formal explanation of it.