Data Types and Variables - Fundamentals - JavaScript for Kids: A Playful Introduction to Programming (2015)

JavaScript for Kids: A Playful Introduction to Programming (2015)

Part I. Fundamentals

Chapter 2. Data Types and Variables

Programming is all about manipulating data, but what is data? Data is information that we store in our computer programs. For example, your name is a piece of data, and so is your age. The color of your hair, how many siblings you have, where you live, whether you’re male or female—these things are all data.

In JavaScript, there are three basic types of data: numbers, strings, and Booleans. Numbers are used for representing, well, numbers! For example, your age can be represented as a number, and so can your height. Numbers in JavaScript look like this:

5;

Strings are used to represent text. Your name can be represented as a string in JavaScript, as can your email address. Strings look like this:

"Hi, I'm a string";

image with no caption

Booleans are values that can be true or false. For example, a Boolean value about you would be whether you wear glasses. Another could be whether you like broccoli. A Boolean looks like this:

true;

There are different ways to work with each data type. For example, you can multiply two numbers, but you can’t multiply two strings. With a string, you can ask for the first five characters. With Booleans, you can check to see whether two values are both true. The following code example illustrates each of these possible operations.

99 * 123;

12177

"This is a long string".slice(0, 4);

"This"

true && false;

false

All data in JavaScript is just a combination of these types of data. In this chapter, we’ll look at each type in turn and learn different ways to work with each type.

NOTE

You may have noticed that all of these commands end with a semicolon (;). Semicolons mark the end of a particular JavaScript command or instruction (also called a statement), sort of like the period at the end of a sentence.

Numbers and Operators

JavaScript lets you perform basic mathematical operations like addition, subtraction, multiplication, and division. To make these calculations, we use the symbols +, -, *, and /, which are called operators.

You can use the JavaScript console just like a calculator. We’ve already seen one example, adding together 3 and 4. Let’s try something harder. What’s 12,345 plus 56,789?

12345 + 56789;

69134

That’s not so easy to work out in your head, but JavaScript calculated it in no time.

You can add multiple numbers with multiple plus signs:

22 + 33 + 44;

99

JavaScript can also do subtraction . . .

1000 - 17;

983

and multiplication, using an asterisk . . .

123 * 456;

56088

and division, using a forward slash . . .

12345 / 250;

49.38

You can also combine these simple operations to make something more complex, like this:

1234 + 57 * 3 - 31 / 4;

1397.25

Here it gets a bit tricky, because the result of this calculation (the answer) will depend on the order that JavaScript does each operation. In math, the rule is that multiplication and division always take place before addition and subtraction, and JavaScript follows this rule as well.

The order of operations: multiplication, division, addition, subtraction

Figure 2-1. The order of operations: multiplication, division, addition, subtraction

Figure 2-1 shows the order JavaScript would follow. First, JavaScript multiplies 57 * 3 and gets 171 (shown in red). Then it divides 31 / 4 to get 7.75 (shown in blue). Next it adds 1234 + 171 to get 1405 (shown in green). Finally it subtracts 1405 - 7.75 to get 1397.25, which is the final result.

What if you wanted to do the addition and the subtraction first, before doing the multiplication and division? For example, say you have 1 brother and 3 sisters and 8 candies, and you want to split the candies equally among your 4 siblings? (You’ve already taken your share!) You would have to divide 8 by your number of siblings.

Here’s an attempt:

8 / 1 + 3;

11

That can’t be right! You can’t give each sibling 11 candies when you’ve only got 8! The problem is that JavaScript does division before addition, so it divides 8 by 1 (which equals 8) and then adds 3 to that, giving you 11. To fix this and make JavaScript do the addition first, we can useparentheses:

8 / (1 + 3);

2

That’s more like it! Two candies to each of your siblings. The parentheses force JavaScript to add 1 and 3 before dividing 8 by 4.

image with no caption

Let’s say your friend is trying to use JavaScript to work out how many balloons to buy. She’s throwing a party and wants everyone to have 2 balloons to blow up. There were originally 15 people coming, but then she invited 9 more. She tries the following code:

15 + 9 * 2;

33

But that doesn’t seem right.

The problem is that the multiplication is happening before the addition. How would you add parentheses to make sure that JavaScript does the addition first? How many balloons does your friend really need?

Variables

JavaScript lets you give names to values using variables. You can think of a variable as a box that you can fit one thing in. If you put something else in it, the first thing goes away.

To create a new variable, use the keyword var, followed by the name of the variable. A keyword is a word that has special meaning in JavaScript. In this case, when we type var, JavaScript knows that we are about to enter the name of a new variable. For example, here’s how you’d make a new variable called nick:

var nick;

undefined

We’ve created a new variable called nick. The console spits out undefined in response. But this isn’t an error! That’s just what JavaScript does whenever a command doesn’t return a value. What’s a return value? Well, for example, when you typed 12345 + 56789;, the console returned the value 69134. Creating a variable in JavaScript doesn’t return a value, so the interpreter prints undefined.

To give the variable a value, use the equal sign:

var age = 12;

undefined

Setting a value is called assignment (we are assigning the value 12 to the variable age). Again, undefined is printed, because we’re creating another new variable. (In the rest of my examples, I won’t show the output when it’s undefined.)

The variable age is now in our interpreter and set to the value 12. That means that if you type age on its own, the interpreter will show you its value:

age;

12

Cool! The value of the variable isn’t set in stone, though (they’re called variables because they can vary), and if you want to update it, just use = again:

age = 13;

13

This time I didn’t use the var keyword, because the variable age already exists. You need to use var only when you want to create a variable, not when you want to change the value of a variable. Notice also, because we’re not creating a new variable, the value 13 is returned from the assignment and printed on the next line.

This slightly more complex example solves the candies problem from earlier, without parentheses:

var numberOfSiblings = 1 + 3;

var numberOfCandies = 8;

numberOfCandies / numberOfSiblings;

2

First we create a variable called numberOfSiblings and assign it the value of 1 + 3 (which JavaScript works out to be 4). Then we create the variable numberOfCandies and assign 8 to it. Finally, we write numberOfCandies / numberOfSiblings. Because numberOfCandies is8 and numberOfSiblings is 4, JavaScript works out 8 / 4 and gives us 2.

Naming Variables

Be careful with your variable names, because it’s easy to misspell them. Even if you just get the capitalization wrong, the JavaScript interpreter won’t know what you mean! For example, if you accidentally used a lowercase c in numberOfCandies, you’d get an error:

numberOfcandies / numberOfSiblings;

ReferenceError: numberOfcandies is not defined

Unfortunately, JavaScript will only do exactly what you ask it to do. If you misspell a variable name, JavaScript has no idea what you mean, and it will display an error message.

Another tricky thing about variable names in JavaScript is that they can’t contain spaces, which means they can be difficult to read. I could have named my variable numberofcandies with no capital letters, which makes it even harder to read because it’s not clear where the words end. Is this variable “numb erof can dies” or “numberofcan dies”? Without the capital letters, it’s hard to tell.

One common way to get around this is to start each word with a capital letter as in NumberOfCandies. (This convention is called camel case because it supposedly looks like the humps on a camel.)

image with no caption

The standard practice is to have variables start with a lowercase letter, so it’s common to capitalize each word except for the first one, like this: numberOfCandies. (I’ll follow this version of the camel case convention throughout this book, but you’re free to do whatever you want!)

Creating New Variables Using Math

You can create new variables by doing some math on older ones. For example, you can use variables to find out how many seconds there are in a year—and how many seconds old you are! Let’s start by finding the number of seconds in an hour.

Seconds in an Hour

First we create two new variables called secondsInAMinute and minutesInAnHour and make them both 60 (because, as we know, there are 60 seconds in a minute and 60 minutes in an hour). Then we create a variable called secondsInAnHour and set its value to the result of multiplying secondsInAMinute and minutesInAnHour. At ➊, we enter secondsInAnHour, which is like saying, “Tell me the value of secondsInAnHour right now!” JavaScript then gives you the answer: it’s 3600.

var secondsInAMinute = 60;

var minutesInAnHour = 60;

var secondsInAnHour = secondsInAMinute * minutesInAnHour;

➊ secondsInAnHour;

3600

Seconds in a Day

Now we create a variable called hoursInADay and set it to 24. Next we create the variable secondsInADay and set it equal to secondsInAnHour multiplied by hoursInADay. When we ask for the value secondsInADay at ➊, we get 86400, which is the number of seconds in a day.

var hoursInADay = 24;

var secondsInADay = secondsInAnHour * hoursInADay;

➊ secondsInADay;

86400

image with no caption

Seconds in a Year

Finally, we create the variables daysInAYear and secondsInAYear. The daysInAYear variable is assigned the value 365, and the variable secondsInAYear is assigned the value of secondsInADay multiplied by daysInAYear. Finally, we ask for the value of secondsInAYear, which is 31536000 (more than 31 million)!

var daysInAYear = 365;

var secondsInAYear = secondsInADay * daysInAYear;

secondsInAYear;

31536000

Age in Seconds

Now that you know the number of seconds in a year, you can easily figure out how old you are in seconds (to the nearest year). For example, as I’m writing this, I’m 29:

var age = 29;

age * secondsInAYear;

914544000

To figure out your age in seconds, enter the same code, but change the value in age to your age. Or just leave out the age variable altogether and use a number for your age, like this:

29 * secondsInAYear;

914544000

I’m more than 900 million seconds old! How many seconds old are you?

Incrementing and Decrementing

As a programmer, you’ll often need to increase or decrease the value of a variable containing a number by 1. For example, you might have a variable that counts the number of high-fives you received today. Each time someone high-fives you, you’d want to increase that variable by 1.

Increasing by 1 is called incrementing, and decreasing by 1 is called decrementing. You increment and decrement using the operators ++ and --.

var highFives = 0;

++highFives;

1

++highFives;

2

--highFives;

1

When we use the ++ operator, the value of highFives goes up by 1, and when we use the -- operator, it goes down by 1. You can also put these operators after the variable. This does the same thing, but the value that gets returned is the value before the increment or decrement.

highFives = 0;

highFives++;

0

highFives++;

1

highFives;

2

In this example, we set highFives to 0 again. When we call highFives++, the variable is incremented, but the value that gets printed is the value before the increment happened. You can see at the end (after two increments) that if we ask for the value of highFives, we get 2.

image with no caption

+= (plus-equals) and –= (minus-equals)

To increase the value of a variable by a certain amount, you could use this code:

var x = 10;

x = x + 5;

x;

15

Here, we start out with a variable called x, set to 10. Then, we assign x + 5 to x. Because x was 10, x + 5 will be 15. What we’re doing here is using the old value of x to work out a new value for x. Therefore, x = x + 5 really means “add 5 to x.”

JavaScript gives you an easier way of increasing or decreasing a variable by a certain amount, with the += and -= operators. For example, if we have a variable x, then x += 5 is the same as saying x = x + 5. The -= operator works in the same way, so x -= 9 would be the same as x = x - 9 (“subtract 9 from x”). Here’s an example using both of these operators to keep track of a score in a video game:

var score = 10;

score += 7;

17

score -= 3;

14

In this example, we start with a score of 10 by assigning the value 10 to the variable score. Then we beat a monster, which increases score by 7 using the += operator. (score += 7 is the same as score = score + 7.) Before we beat the monster, score was 10, and 10 + 7 is 17, so this operation sets score to 17.

After our victory over the monster, we crash into a meteor and score is reduced by 3. Again, score -= 3 is the same as score = score - 3. Because score is 17 at this point, score - 3 is 14, and that value gets reassigned to score.

There are some other operators that are similar to += and -=. For example, there are *= and /=. What do you think these do? Give them a try:

var balloons = 100;

balloons *= 2;

???

What does balloons *= 2 do? Now try this:

var balloons = 100;

balloons /= 4;

???

What does balloons /= 4 do?

Strings

So far, we’ve just been working with numbers. Now let’s look at another type of data: strings. Strings in JavaScript (as in most programming languages) are just sequences of characters, which can include letters, numbers, punctuation, and spaces. We put strings between quotes so JavaScript knows where they start and end. For example, here’s a classic:

"Hello world!";

"Hello world!"

To enter a string, just type a double quotation mark (") followed by the text you want in the string, and then close the string with another double quote. You can also use single quotes ('), but to keep things simple, we’ll just be using double quotes in this book.

You can save strings into variables, just like numbers:

var myAwesomeString = "Something REALLY awesome!!!";

There’s also nothing stopping you from assigning a string to a variable that previously contained a number:

var myThing = 5;

myThing = "this is a string";

"this is a string"

What if you put a number between quotes? Is that a string or a number? In JavaScript, a string is a string (even if it happens to have some characters that are numbers). For example:

var numberNine = 9;

var stringNine = "9";

numberNine is a number, and stringNine is a string. To see how these are different, let’s try adding them together:

numberNine + numberNine;

18

stringNine + stringNine;

"99"

When we add the number values 9 and 9, we get 18. But when we use the + operator on "9" and "9", the strings are simply joined together to form "99".

image with no caption

Joining Strings

As you just saw, you can use the + operator with strings, but the result is very different from using the + operator with numbers. When you use + to join two strings, you make a new string with the second string attached to the end of the first string, like this:

var greeting = "Hello";

var myName = "Nick";

greeting + myName;

"HelloNick"

Here, we create two variables (greeting and myName) and assign each a string value ("Hello" and "Nick", respectively). When we add these two variables together, the strings are combined to make a new string, "HelloNick".

That doesn’t look right, though—there should be a space between Hello and Nick. But JavaScript won’t put a space there unless we specifically tell it to by adding a space in one of the original strings:

➊ var greeting = "Hello ";

var myName = "Nick";

greeting + myName;

"Hello Nick"

The extra space inside the quotes at ➊ puts a space in the final string as well.

You can do a lot more with strings other than just adding them together. Here are some examples.

Finding the Length of a String

To get the length of a string, just add .length to the end of it.

"Supercalifragilisticexpialidocious".length;

34

You can add .length to the end of the actual string or to a variable that contains a string:

var java = "Java";

java.length;

4

var script = "Script";

script.length;

6

var javascript = java + script;

javascript.length;

10

Here we assign the string "Java" to the variable java and the string "Script" to the variable script. Then we add .length to the end of each variable to determine the length of each string, as well as the length of the combined strings.

Notice that I said you can add .length to “the actual string or to a variable that contains a string.” This illustrates something very important about variables: anywhere you can use a number or a string, you can also use a variable containing a number or a string.

Getting a Single Character from a String

Sometimes you want to get a single character from a string. For example, you might have a secret code where the message is made up of the second character of each word in a list of words. You’d need to be able to get just the second characters and join them all together to create a new word.

To get a character from a particular position in a string, use square brackets, [ ]. Just take the string, or the variable containing the string, and put the number of the character you want in a pair of square brackets at the end. For example, to get the first character of myName, use myName[0], like this:

var myName = "Nick";

myName[0];

"N"

myName[1];

"i"

myName[2];

"c"

Notice that to get the first character of the string, we use 0 rather than 1. That’s because JavaScript (like many other programming languages) starts counting at zero. That means when you want the first character of a string, you use 0; when you want the second one, you use 1; and so on.

Let’s try out our secret code, where we hide a message in some words’ second characters. Here’s how to find the secret message in a sequence of words:

var codeWord1 = "are";

var codeWord2 = "tubas";

var codeWord3 = "unsafe";

var codeWord4 = "?!";

codeWord1[1] + codeWord2[1] + codeWord3[1] + codeWord4[1];

"run!"

Again, notice that to get the second character of each string, we use 1.

Cutting Up Strings

To “cut off” a piece of a big string, you can use slice. For example, you might want to grab the first bit of a long movie review to show as a teaser on your website. To use slice, put a period after a string (or a variable containing a string), followed by the word slice and opening and closing parentheses. Inside the parentheses, enter the start and end positions of the slice of the string you want, separated by a comma. Figure 2-2 shows how to use slice.

How to use slice to get characters from a string

Figure 2-2. How to use slice to get characters from a string

For example:

var longString = "My long string is long";

longString.slice(3, 14);

"long string"

The first number in parentheses is the number of the character that begins the slice, and the second number is the number of the character after the last character in the slice. Figure 2-3 shows which characters this retrieves, with the start value (3) and stop value (14) highlighted in blue.

In the example above, slice grabs the characters shown in the gray box.

Figure 2-3. In the example above, slice grabs the characters shown in the gray box.

Here we basically tell JavaScript, “Pull a slice out of this longer string starting at the character at place 3 and keep going until you hit place 14.”

If you include only one number in the parentheses after slice, the string that it slices will start from that number and continue all the way to the end of the string, like this:

var longString = "My long string is long";

longString.slice(3);

"long string is long"

Changing Strings to All Capital or All Lowercase Letters

If you have some text that you just want to shout, try using toUpperCase to turn it all into capital letters.

"Hello there, how are you doing?".toUpperCase();

"HELLO THERE, HOW ARE YOU DOING?"

When you use .toUpperCase() on a string, it makes a new string where all the letters are turned into uppercase.

You can go the other way around, too:

"hELlo THERE, hOW ARE yOu doINg?".toLowerCase();

"hello there, how are you doing?"

As the name suggests, .toLowerCase() makes all of the characters lowercase. But shouldn’t sentences always start with a capital letter? How can we take a string and make the first letter uppercase but turn the rest into lowercase?

NOTE

See if you can figure out how to turn "hELlo THERE, hOW ARE yOu doINg?" into "Hello there, how are you doing?" using the tools you just learned. If you get stuck, review the sections on getting a single character and using slice. Once you’re done, come back and have a look at how I did it.

Here’s one approach:

➊ var sillyString = "hELlo THERE, hOW ARE yOu doINg?";

➋ var lowerString = sillyString.toLowerCase();

➌ var firstCharacter = lowerString[0];

➍ var firstCharacterUpper = firstCharacter.toUpperCase();

➎ var restOfString = lowerString.slice(1);

➏ firstCharacterUpper + restOfString;

"Hello there, how are you doing?"

Let’s go through this line by line. At ➊, we create a new variable called sillyString and save the string we want to modify to that variable. At ➋, we get the lowercase version of sillyString ("hello there how are you doing?") with .toLowerCase() and save that in a new variable called lowerString.

image with no caption

At ➌, we use [0] to get the first character of lowerString ("h") and save it in firstCharacter (0 is used to grab the first character). Then, at ➍, we create an uppercase version of firstCharacter ("H") and call that firstCharacterUpper.

At ➎, we use slice to get all the characters in lowerString, starting from the second character ("ello there how are you doing?") and save that in restOfString. Finally, at ➏, we add firstCharacterUpper ("H") to restOfString to get "Hello there, how are you doing?".

Because values and variables can be substituted for each other, we could turn lines ➋ through ➏ into just one line, like this:

var sillyString = "hELlo THERE, hOW ARE yOu doINg?";

sillyString[0].toUpperCase() + sillyString.slice(1).toLowerCase();

"Hello there, how are you doing?"

It can be confusing to follow along with code written this way, though, so it’s a good idea to use variables for each step of a complicated task like this—at least until you get more comfortable reading this kind of complex code.

Booleans

Now for Booleans. A Boolean value is simply a value that’s either true or false. For example, here’s a simple Boolean expression.

var javascriptIsCool = true;

javascriptIsCool;

true

In this example, we created a new variable called javascriptIsCool and assigned the Boolean value true to it. On the second line, we get the value of javascriptIsCool, which, of course, is true!

Logical Operators

Just as you can combine numbers with mathematical operators (+, -, *, /, and so on), you can combine Boolean values with Boolean operators. When you combine Boolean values with Boolean operators, the result will always be another Boolean value (either true or false).

The three main Boolean operators in JavaScript are &&, ||, and !. They may look a bit weird, but with a little practice, they’re not hard to use. Let’s try them out.

&& (and)

&& means “and.” When reading aloud, people call it “and,” “andand,” or “ampersand-ampersand.” (Ampersand is the name of the character &.) Use the && operator with two Boolean values to see if they’re both true.

For example, before you go to school, you want to make sure that you’ve had a shower and you have your backpack. If both are true, you can go to school, but if one or both are false, you can’t leave yet.

var hadShower = true;

var hasBackpack = false;

hadShower && hasBackpack;

false

Here we set the variable hadShower to true and the variable hasBackpack to false. When we enter hadShower && hasBackpack, we are basically asking JavaScript, “Are both of these values true?” Since they aren’t both true (you don’t have your backpack), JavaScript returnsfalse (you’re not ready for school).

image with no caption

Let’s try this again, with both values set to true:

var hadShower = true;

var hasBackpack = true;

hadShower && hasBackpack;

true

Now JavaScript tells us that hadShower && hasBackpack is true. You’re ready for school!

|| (or)

The Boolean operator || means “or.” It can be pronounced “or,” or even “or-or,” but some people call it “pipes,” because programmers call the | character a pipe. You can use this operator with two Boolean values to find out whether either one is true.

For example, say you’re still getting ready to go to school and you need to take a piece of fruit for lunch, but it doesn’t matter whether you take an apple or an orange or both. You can use JavaScript to see whether you have at least one, like this:

var hasApple = true;

var hasOrange = false;

hasApple || hasOrange;

true

hasApple || hasOrange will be true if either hasApple or hasOrange is true, or if both are true. But if both are false, the result will be false (you don’t have any fruit).

! (not)

! just means “not.” You can call it “not,” but lots of people call it “bang.” (An exclamation point is sometimes called a bang.) Use it to turn false into true or true into false. This is useful for working with values that are opposites. For example:

var isWeekend = true;

var needToShowerToday = !isWeekend;

needToShowerToday;

false

In this example, we set the variable isWeekend to true. Then we set the variable needToShowerToday to !isWeekend. The bang converts the value to its opposite—so if isWeekend is true, then !isWeekend is not true (it’s false). So when we ask for the value ofneedToShowerToday, we get false (you don’t need to shower today, because it’s the weekend).

Because needToShowerToday is false, !needToShowerToday will be true:

needToShowerToday;

false

!needToShowerToday;

true

In other words, it’s true that you do not need to shower today.

Combining logical operators

Operators get interesting when you start combining them. For example, say you should go to school if it’s not the weekend and you’ve showered and you have an apple or you have an orange. We could check whether all of this is true with JavaScript, like this:

var isWeekend = false;

var hadShower = true;

var hasApple = false;

var hasOrange = true;

var shouldGoToSchool = !isWeekend && hadShower && (hasApple || hasOrange);

shouldGoToSchool;

true

In this case, it’s not the weekend, you have showered, and you don’t have an apple but you do have an orange—so you should go to school.

hasApple || hasOrange is in parentheses because we want to make sure JavaScript works out that bit first. Just as JavaScript calculates * before + with numbers, it also calculates && before || in logical statements.

Comparing Numbers with Booleans

Boolean values can be used to answer questions about numbers that have a simple yes or no answer. For example, imagine you’re running a theme park and one of the rides has a height restriction: riders must be at least 60 inches tall, or they might fall out! When someone wants to go on the ride and tells you their height, you need to know if it’s greater than this height restriction.

Greater Than

We can use the greater-than operator (>) to see if one number is greater than another. For example, to see if the rider’s height (65 inches) is greater than the height restriction (60 inches), we could set the variable height equal to 65 and the variable heightRestriction equal to 60, and then use > to compare the two:

image with no caption

var height = 65;

var heightRestriction = 60;

height > heightRestriction;

true

With height > heightRestriction, we’re asking JavaScript to tell us whether the first value is greater than the second. In this case, the rider is tall enough!

What if a rider were exactly 60 inches tall, though?

var height = 60;

var heightRestriction = 60;

height > heightRestriction;

false

Oh no! The rider isn’t tall enough! But if the height restriction is 60, then shouldn’t people who are exactly 60 inches be allowed in? We need to fix that. Luckily, JavaScript has another operator, >=, which means “greater than or equal to”:

var height = 60;

var heightRestriction = 60;

height >= heightRestriction;

true

Good, that’s better—60 is greater than or equal to 60.

Less Than

The opposite of the greater-than operator (>) is the less-than operator (<). This operator might come in handy if a ride were designed only for small children. For example, say the rider’s height is 60 inches, but riders must be no more than 48 inches tall:

var height = 60;

var heightRestriction = 48;

height < heightRestriction;

false

We want to know if the rider’s height is less than the restriction, so we use <. Because 60 is not less than 48, we get false (someone whose height is 60 inches is too tall for this ride).

And, as you may have guessed, we can also use the operator <=, which means “less than or equal to”:

var height = 48;

var heightRestriction = 48;

height <= heightRestriction;

true

Someone who is 48 inches tall is still allowed to go on the ride.

Equal To

To find out if two numbers are exactly the same, use the triple equal sign (===), which means Equal To. But be careful not to confuse === with a single equal sign (=), because === means “are these two numbers equal?” and = means “save the value on the right in the variable on the left.” In other words, === asks a question, while = assigns a value to a variable.

image with no caption

When you use =, a variable name has to be on the left and the value you want to save to that variable must be on the right. On the other hand, === is just used for comparing two values to see if they’re the same, so it doesn’t matter which value is on which side.

For example, say you’re running a competition with your friends Chico, Harpo, and Groucho to see who can guess your secret number, which is 5. You make it easy on your friends by saying that the number is between 1 and 9, and they start to guess. First you set mySecretNumber equal to 5. Your first friend, Chico, guesses that it’s 3 (chicoGuess). Let’s see what happens next:

var mySecretNumber = 5;

var chicoGuess = 3;

mySecretNumber === chicoGuess;

false

var harpoGuess = 7;

mySecretNumber === harpoGuess;

false

var grouchoGuess = 5;

mySecretNumber === grouchoGuess;

true

The variable mySecretNumber stores your secret number. The variables chicoGuess, harpoGuess, and grouchoGuess represent your friends’ guesses, and we use === to see whether each guess is the same as your secret number. Your third friend, Groucho, wins by guessing 5.

When you compare two numbers with ===, you get true only when both numbers are the same. Because grouchoGuess is 5 and mySecretNumber is 5, mySecretNumber === grouchoGuess returns true. The other guesses didn’t match mySecretNumber, so they returned false.

You can also use === to compare two strings or two Booleans. If you use === to compare two different types—for example, a string and a number—it will always return false.

Double Equals

Now to confuse things a bit: there’s another JavaScript operator (double equals, or ==) that means “equal-ish.” Use this to see whether two values are the same, even if one is a string and the other is a number. All values have some kind of type. So the number 5 is different from the string"5", even though they basically look like the same thing. If you use === to compare the number 5 and the string "5", JavaScript will tell you they’re not equal. But if you use == to compare them, it will tell you they’re the same:

var stringNumber = "5";

var actualNumber = 5;

stringNumber === actualNumber;

false

stringNumber == actualNumber;

true

At this point, you might be thinking to yourself, “Hmm, it seems much easier to use double equals than triple equals!” You have to be very careful, though, because double equals can be very confusing. For example, do you think 0 is equal to false? What about the string "false"? When you use double equals, 0 is equal to false, but the string "false" is not:

0 == false;

true

"false" == false;

false

This is because when JavaScript tries to compare two values with double equals, it first tries to make them the same type. In this case, it converts the Boolean into a number. If you convert Booleans to numbers, false becomes 0, and true becomes 1. So when you type 0 == false, you get true!

Because of this weirdness, it’s probably safest to just stick with === for now.

You’ve been asked by the local movie theater managers to implement some JavaScript for a new automated system they’re building. They want to be able to work out whether someone is allowed into a PG-13 movie or not.

The rules are, if someone is 13 or over, they’re allowed in. If they’re not over 13, but they are accompanied by an adult, they’re also allowed in. Otherwise, they can’t see the movie.

var age = 12;

var accompanied = true;

???

Finish this example using the age and accompanied variables to work out whether this 12-year-old is allowed to see the movie. Try changing the values (for example, set age to 13 and accompanied to false) and see if your code still works out the right answer.

image with no caption

undefined and null

Finally, we have two values that don’t fit any particular mold. They’re called undefined and null. They’re both used to mean “nothing,” but in slightly different ways.

undefined is the value JavaScript uses when it doesn’t have a value for something. For example, when you create a new variable, if you don’t set its value to anything using the = operator, its value will be set to undefined:

var myVariable;

myVariable;

undefined

The null value is usually used when you want to deliberately say “This is empty.”

var myNullVariable = null;

myNullVariable;

null

At this point, you won’t be using undefined or null very often. You’ll see undefined if you create a variable and don’t set its value, because undefined is what JavaScript will always give you when it doesn’t have a value. It’s not very common to set something to undefined; if you feel the need to set a variable to “nothing,” you should use null instead.

null is used only when you actually want to say something’s not there, which is very occasionally helpful. For example, say you’re using a variable to track what your favorite vegetable is. If you hate all vegetables and don’t have a favorite, you might set the favorite vegetable variable tonull.

Setting the variable to null would make it obvious to anyone reading the code that you don’t have a favorite vegetable. If it were undefined, however, someone might just think you hadn’t gotten around to setting a value yet.

What You Learned

Now you know all the basic data types in JavaScript—numbers, strings, and Booleans—as well as the special values null and undefined. Numbers are used for math-type things, strings are used for text, and Booleans are used for yes or no questions. The values null and undefined are there to give us a way to talk about things that don’t exist.

In the next two chapters, we’ll look at arrays and objects, which are both ways of joining basic types to create more complex collections of values.