Getting Started

The Console

Compared to other programming languages, getting started with JavaScript is incredibly easy. You don't need a special editor. You don't need a compiler or other complicated tools. In fact, you don't even need to create any files or upload anything to a server. We're going to complete this first section using nothing more than the browser window you've already got open.

The modern web browser is an impressive beast, and it includes many of the tools that you need not just to run JavaScript, but also to write it. Let's take a look at the first of these tools by opening up the console. All browsers include a console, although they keep them in different locations:

The console should have a blinking cursor next to a ">", just waiting for you to start typing something. Type the following line, then press the "Enter" key. 2 + 2; You should see two more lines added to the console: first a line containing the command you just typed, and then the result (hopefully "4"). Congratulations! You've just become a JavaScript programmer!

The code "2 + 2" is what we call an expression. An expression is any JavaScript code that can be reduced down into a value (4, in this case). The simplest expression possible is just a number value on its own, without any kind of operation. Expressions can be built out of smaller expressions, like so: 1 + 2 * 3;

The * in this code sample means "multiply" (to divide, use /). JavaScript uses the same rules of mathematical order that you learned in grade school: parentheses, exponents, multiplication, division, addition, and subtraction, in that order. So when JavaScript evaluates that expression, it first multiplies 2 and 3, then adds 1, for a final result of 7. Try it in the console now, if you'd like to double-check my math. If you'd like to change the order so that the 1 and 2 are added together before multiplying by 3, just add parentheses: (1 + 2) * 3;

At the end of our statements, we add a semicolon to let JavaScript know that we're done with that line. If you leave it off, the code will still work. But it's helpful to explicitly let the browser know that you're done with that particular thought, the same way that we end our sentences with punctuation even if the meaning is clear without any.

Often, when we are working with expressions, we may want to store the result so that we can use it later. For example, when balancing your checkbook, you might keep track of several subtotals within your budget (entertainment, food, rent) in order to see where your money is going. You wouldn't want to have to add up each subtotal every time you compared rent money to gas money.

We can hold onto a value in JavaScript by assigning it to a variable. A variable is like a nickname that we assign to that value. So we might keep track of our work so far using the following code: var result = 1 + 2 * 3;

In this statement, we do four things:

  1. We use the var keyword to tell JavaScript that we are declaring a variable.
  2. Next we write the name of the variable (in this case, "result"). Variable names can be any combination of letters and numbers with no spaces between them, but they must start with a letter. Uppercase and lowercase letters mean different things, so dog and Dog are two different variables.
  3. We write an equals sign to assign the value. In JavaScript, = does not mean "equals." Instead, it means to take the value on the right, and assign it to the variable on the left.
  4. Finally, we write the expression that will have its value assigned to the variable.

Our variable result now contains the value 7. If we want to use that value, we can just write the variable name into a new expression, like so: 21 * 3 / result When JavaScript evaluates this line of code, it'll substitute the value of result into the expression, making it look like this: 21 * 3 / 7

Once it's assigned, a variable holds onto its value until we reassign it. To reassign it, just use the = operator again. You don't have to write var this time, only the first time that you declare a variable (after that, the browser knows that it exists). So we might decide we want our new result to be 8: result = 8 We can even reassign a variable to the value of an expression that includes itself, changing it relative to its previous value. For example, we might take the number that's currently in result, add some difference up or down, and save it back in the result for a running total. result = result + .5;


So far, we've been working with numberical values exclusively, but JavaScript actually has several types of values that it can use in its expressions and store in variables. The most basic kinds of values JavaScript can store, otherwise known as the primitive types, are numbers, strings, and Booleans. We've already seen how numbers can work, so how about the others?


A string is the programming language name for a chunk of text. We write strings in JavaScript by surrounding them with quotes. The type of quote doesn't matter--you can use double or single--as long as it begins and ends with the same kind. The following example shows a pair of variables containing strings quoted in both ways. var president = "Abraham Lincoln"; var route = 'Lincoln Tunnel';

Sometimes, though, we need to use both types of quotes inside of a string. If that's the case, we can escape the quotes that we want to go inside of the text by putting a backslash in front of them. '"Four score and seven years ago," begins Lincoln\'s Gettysburg Address.'

Here, give it a try for yourself. In the following input boxes, there are some strings that haven't been escaped properly. As a result, they are going to break when the browser tries to run them. Add slashes before the quotes that need to be escaped, and the boxes will turn green.

You can combine strings by using the + operator, just like adding numbers together. Obviously, this works with variables too, which can save you a lot of typing. But remember, the strings will be combined directly. JavaScript doesn't understand English or grammar. You'll have to be careful to include spaces if you want them. var best = "It was the best of times."; var worst = "It was the worst of times."; var combined = best + " " + worst; "It was the best of times. It was the worst of times."

Unfortunately, none of the other math operators work on strings. It would be nice to be able to subtract text from a sentence, but if you try, you'll get the result NaN. Contrary to what you'd think, this is not a delicious form of Indian bread. It stands for Not a Number, and is the result of trying to do math on non-math variable types in JavaScript.


Computers are binary machines: at the lowest level, everything is about on and off, ones and zeros. In JavaScript, we're pretty distant from that lowest level, and we rarely--if ever--interact with binary code. But there is a variable type that's a lot like binary, in that it's restricted to two states: true and false. This is the Boolean type, named after George Boole, who invented a kind of math that only works with true and false values. var t = true; var f = false;

We'll deal more with Boolean values in the next section. For right now, what's important to remember is that when you're working with these, don't put true and false in quotes. They're not strings, they're real values in JavaScript, just like numbers are.

Inspecting variables with typeof

We know what the type of a variable is when we create it, obviously. But after a few expressions and assignments, it may not be entirely clear, because JavaScript will try to convert values to be helpful. Many times, this is actually what we want. For example, let's say we want to combine a number with a string, which is not an uncommon thing to do. var accountBalance = 123.45; var remaining = "You have $" + accountBalance + " remaining in your account."; "You have $123.45 remaining in your account." In this case, the number will be converted to a string for us, and combined with the other strings into a single sentence. That's good! But sometimes this automatic conversion isn't what we want. If we add two values together, thinking that they're both numbers, but one is a string, they'll get combined end-to-end instead of added together. In this case, we wanted the value 3, but we're not going to get it. var numeric = 1; var text = "2"; var added = numeric + text; "12"

This is more common than you might think, because many input functions in JavaScript return strings, even if the user types a number. So you may be asking for a numerical value, but what you have is a string of text instead. How do we know if a variable is the right type? We can ask using the typeof operator. typeof "this is a string" "string" typeof 1.234 "number" typeof true "boolean"

typeof returns a string containing the type of the variable being inspected. Once we know that a variable isn't what we want it to be, we can convert it between types with some simple operations. To convert a number to a string, you can use the String() function. A function is a special kind of JavaScript command. For now, you only need to know that functions are usually followed by parentheses, and the value we want to be changed or used by the function goes between them. The function then evaluates to a value just like any other expression--in this case, it converts the number value into a text string. var num = 2; var text = String(num);

We can go the other way using the Number() function. You can also convert a string to a number by using the parseFloat function that's built-in to JavaScript ("float" refers to "floating point," meaning a number with a decimal point--some languages also use "fixed" point, where the decimal is always in the same place, but JavaScript isn't one of them). var text = "2"; num = Number(text); var float = parseFloat(text);

Converting items to booleans is a somewhat more involved topic, and one we'll address in the next chapter. But first, we need to learn how to write scripts into our web pages, not just using the console.

Example Code

The more you practice using the browser console, the more natural it will become. It's a great way to experiment with JavaScript before writing a real script, or to see errors that have occurred. Practice by running the following lines in the console to accomplish a simple math problem: find out how long it takes a bus to travel at maximum highway speed on a route that includes 100 miles at 55MPH, 50 miles at 45MPH, and 230 miles at 70MPH. var firstLegTime = 100 / 55; var secondLegTime = 50 / 45; var thirdLegTime = 230 / 70; var totalHours = firstLegTime + secondLegTime + thirdLegTime; var solution = "The total time required is " + totalHours + " hours"; solution; The total time required is 6.2150072150072155 hours.

Exercises and Discussion Questions

  1. What are the three primitive types in JavaScript that we've discussed in this chapter?
  2. What's the result of "typeof '12'"? What about "typeof 12"?
  3. What's the best way to convert from a number to a string, and vice versa?
  4. Say you typed the code "'one' - 2" into the console. What will you see as the result?