Introduction to DataTypes and Values

We'll start with an article that describes how a computer stores values and some primitive types such as numbers and strings. You can think of the "type of a value" as defining how it is stored, named, and manipulated. For example, a calculator program uses the type "number", which holds "numeric values" and supports "arithmetic operations". JavaScript has two types: "primitive" and "object". Examples of primitive types include numbers, strings, and Booleans. Object types include arrays, objects, and functions.

Here are some things to remember when using JavaScript data types:

  • Primitive types are "immutable"; their "values" cannot be changed once created;
  • Object types are "mutable"; their values can change once created; and
  • Although JavaScript supports types, it is a "dynamically typed" language, which means that you do not have to define the type of variable in a JavaScript program (but this is not a best practice).

Arithmetic

The main thing to do with numbers is arithmetic. Arithmetic operations such as addition or multiplication take two number values and produce a new number from them. Here is what they look like in JavaScript:

100 + 4 * 11

The + and * symbols are called operators. The first stands for addition, and the second stands for multiplication. Putting an operator between two values will apply it to those values and produce a new value.

But does the example mean "add 4 and 100, and multiply the result by 11," or is the multiplication done before the adding? As you might have guessed, the multiplication happens first. But as in mathematics, you can change this by wrapping the addition in parentheses.

(100 + 4) * 11

For subtraction, there is the - operator, and division can be done with the / operator.

When operators appear together without parentheses, the order in which they are applied is determined by the precedence of the operators. The example shows that multiplication comes before addition. The / operator has the same precedence as *. Likewise for + and -. When multiple operators with the same precedence appear next to each other, as in 1 - 2 + 1, they are applied left to right: (1 - 2) + 1.

These rules of precedence are not something you should worry about. When in doubt, just add parentheses.

There is one more arithmetic operator, which you might not immediately recognize. The % symbol is used to represent the remainder operation. X % Y is the remainder of dividing X by Y. For example, 314 % 100 produces 14, and 144 % 12 gives 0. The remainder operator's precedence is the same as that of multiplication and division. You'll also often see this operator referred to as modulo.