Chapter 1
Values, Types, and Operators

At the core, programming is just about following instructions. You, as the programmer, will write instructions that the computer will follow.

A simple program is:

1 + 2

Which tells the computer, as you were told when first learning arithmetic, to add the numbers 1 and 2 together. The result of this program is the number 3.

While this program evaluates to 3, we haven’t told the computer what to do with that value. So it won’t do anything, and we won’t see any result if we run the program above.

One of the most common things we want to do is print values to the screen. This is helpful not only in figuring out if our programs are working, but also to let people actually use them. In Javascript (NOTE: This uses functionality from the TLC library code, but there is a similar built in operator called console.log), we can print a value to the screen with the print operation. This is done like:

print(1 + 2)

You put what you want to print out inside the parethesis that follow print. This might remind you of functions in algebra class, where you may have seen f(x) or similar. We’ll see a lot of different operations, and soon be writing our own!

If you want to print multiple expressions out, you can do that as well:

print(1 + 2);
print(3 - 2);

We put ; at the end of the line to indicate that we are doing multiple things. Generally, you should do this after each line, though sometimes Javascript will permit you to skip them.

You can also do other basic arithmetic, and you can write more complicated expressions:

print(1 + 2 * 3 - 4)

Like human languages, programming languages have a grammar, which often allows certain expressions (or entire programs) to be embedded within other programs, as we can see with our program 1 + 2 embedded within print() in the second example. As in arithmetic, sometimes a program could be ambiguous. For example, in the previous example, if we first evaluated 1 + 2 before multiplying by 3 we would get a different answer. These kind of ambiguities are resolved in the same way as arithmetic—with rules of "precedence" (what operations "precede" others) and parenthesis to override them.

As an exercise, consider the following:

print((1 + 2) * 3 - 4)

This prints out 5 right now. Try adding parenthesis so that it prints out -3. Now try changing the parenthesis so that it prints out 3.

Strings

But programs aren’t all about numbers! Indeed, most programs deal with more interesting forms of data. "Strings" are used to represent text. They are written by enclosing their content in quotes.

"Patch my boat with chewing gum"
'Monkeys wave goodbye'

Both single and double quotes can be used to mark strings as long as the quotes at the start and the end of the string match.

You can also print out strings:

print("Patch my boat with chewing gum")

Almost anything can be put between quotes, and JavaScript will make a string value out of it. But a few characters are more difficult. You can imagine how putting quotes between quotes might be hard. Newlines (the characters you get when you press Enter) also can’t be put between quotes. The string has to stay on a single line.

To make it possible to include such characters in a string, the following notation is used: whenever a backslash (\) is found inside quoted text, it indicates that the character after it has a special meaning. This is called escaping the character. A quote that is preceded by a backslash will not end the string but be part of it. When an n character occurs after a backslash, it is interpreted as a newline. Similarly, a t after a backslash means a tab character. Take the following string:

"This is the first line\nAnd this is the second"

The actual text contained is this:

This is the first line
And this is the second

There are, of course, situations where you want a backslash in a string to be just a backslash, not a special code. If two backslashes follow each other, they will collapse together, and only one will be left in the resulting string value. This is how the string “A newline character is written like "\n".” can be expressed:

"A newline character is written like \"\\n\"."

Strings cannot be divided, multiplied, or subtracted, but the + operator can be used on them. It does not add, but it concatenates—it glues two strings together. The following line will produce the string "concatenate":

print("con" + "cat" + "e" + "nate")

Images

We can also draw pictures. The TLC.js library adds a few basic functions that create pictures, and ways of combining them to create new pictures. One of the most basic ones is a circle. You can create a small red circle by writing circle(10, "red"), where 10 is the radius and red indicates the color of the pixels.

Like with normal values, you have to tell Javascript to print images:

print(circle(10, "red"))

We can also draw rectangles, which are created with a width, height, and color:

print(rectangle(80, 30, "black"))

But plain rectangles and circles are a little boring. Fortunately, we can combine them together with the operator overlay, which takes as arguments two images, and places the first on the center of the second. The resulting image will be the same size as the second one, so if the first image is bigger, you may get strange (and interesting!) results. For example:

print(overlay(rectangle(20, 20, "red"), rectangle(80, 30, "black")))

Of course, the result of overlay-ing two images is another image, which means it too can be the input for another overlay.

What kind of pictures can you draw with this?

What are the limitations?

Boolean values

Often, you will need a value that simply distinguishes between two possibilities, like “yes” and “no,” or “on” and “off.” For this, JavaScript has a Boolean type, which has just two values: true and false (which are written simply as those words).

Comparisons

Here is one way to produce Boolean values:

print(3 > 2)
// → true
print(3 < 2)
// → false

The > and < signs are the traditional symbols for “is greater than” and “is less than”, respectively. They are binary operators. Applying them results in a Boolean value that indicates whether they hold true in this case.

Strings can be compared in the same way.

print("Aardvark" < "Zoroaster")
// → true

The way strings are ordered is more or less alphabetic: uppercase letters are always “less” than lowercase ones, so "Z" < "a" is true, and non-alphabetic characters (!, -, and so on) are also included in the ordering. The actual comparison is based on the Unicode standard. This standard assigns a number to virtually every character you would ever need, including characters from Greek, Arabic, Japanese, Tamil, and so on. When comparing strings, JavaScript goes over them from left to right, comparing the numeric codes of the characters one by one.

Other similar operators are >= (greater than or equal to), <= (less than or equal to), === (equal to), and !== (not equal to).

print("Itchy" !== "Scratchy")
// → true

There is only one value in JavaScript that is not equal to itself, and that is NaN, which stands for “not a number”.

print(NaN === NaN)
// → false

NaN is supposed to denote the result of a nonsensical computation, and as such, it isn’t equal to the result of any other nonsensical computations.

Logical operators

There are also some operations that can be applied to Boolean values themselves. JavaScript supports three logical operators: and, or, and not. These can be used to “reason” about Booleans.

The && operator represents logical and. It is a binary operator, and its result is true only if both the values given to it are true.

print(true && false)
// → false
print(true && true)
// → true

The || operator denotes logical or. It produces true if either of the values given to it is true.

print(false || true)
// → true
print(false || false)
// → false

Not is written as an exclamation mark (!). It is a unary operator that flips the value given to it — !true produces false and !false gives true.

When mixing these Boolean operators with arithmetic and other operators, it is not always obvious when parentheses are needed. In practice, you can usually get by with knowing that of the operators we have seen so far, || has the lowest precedence, then comes &&, then the comparison operators (>, ===, and so on), and then the rest. This order has been chosen such that, in typical expressions like the following one, as few parentheses as possible are necessary:

1 + 1 === 2 && 10 * 10 > 50

But, to make your life easier, it is safer to just include parenthesis!

Undefined values

There are two special values, written null and undefined, that are used to denote the absence of a meaningful value. They are themselves values, but they carry no information.

Many operations in the language that don’t produce a meaningful value (you’ll see some later) yield undefined simply because they have to yield some value.

The difference in meaning between undefined and null is an accident of JavaScript’s design, and it doesn’t matter most of the time. In the cases where you actually have to concern yourself with these values, we recommend treating them as interchangeable (more on that in a moment).

Automatic type conversion

JavaScript goes out of its way to accept almost any program you give it, even programs that do odd things. This is nicely demonstrated by the following expressions:

print(8 * null)
// → 0
print("5" - 1)
// → 4
print("5" + 1)
// → 51
print("five" * 2)
// → NaN

When an operator is applied to the “wrong” type of value, JavaScript will quietly convert that value to the type it wants, using a set of rules that often aren’t what you want or expect. This is called type coercion. So the null in the first expression becomes 0, and the "5" in the second expression becomes 5 (from string to number). Yet in the third expression, + tries string concatenation before numeric addition, so the 1 is converted to "1" (from number to string).

This can be really confusing and hard to figure out, so you should not depend on it in your programs.

Summary

We looked at four types of JavaScript values in this chapter: numbers, strings, Booleans, and undefined values.

Such values are created by typing in their name (true, null) or value (13, "abc"). You can combine and transform values with operators. We saw binary operators for arithmetic (+, -, *, /, and %), string concatenation (+), comparison (===, !==, <, >, <=, >=), and logic (&&, ||).

This gives you enough information to use JavaScript as a pocket calculator, but not much more. The next chapter will start tying these expressions together into basic programs.

Exercises

As an exercise, try creating some interesting drawings.

For example, draw a cat!

Or a panda:

A panda