Stoyan Stefanov
Primitive Data Types
Any value that you use is of a certain type. In JavaScript, there are the following primitive data types:
- Number—this includes floating point numbers as well as integers, for example 1, 100, 3.14.
- String—any number of characters, for example "a", "one", "one 2 three".
- Boolean—can be either
true
orfalse
. - Undefined—when you try to access a variable that doesn't exist, you get the special value
undefined
. The same will happen when you have declared a variable, but not given it a value yet. JavaScript will initialize it behind the scenes, with the valueundefined
. - Null—this is another special data type that can have only one value, the
null
value. It means no value, an empty value, nothing. The difference withundefined
is that if a variable has a valuenull
, it is still defined, it only happens that its value is nothing. You'll see some examples shortly.
null
is considered an object, which is a little awkward—having an object (something) that is actually nothing. We'll dive into objects in Chapter 4, but for the time being just remember that in JavaScript the data types are either:
- Primitive (the five types listed above), or
- Non-primitive (objects)
Finding out the Value Type —the typeof Operator
If you want to know the data type of a variable or a value, you can use the special typeof
operator. This operator returns a string that represents the data type. The return values of using typeof can be one of the following—"number", "string", "boolean", "undefined", "object", or "function". In the next few sections, you'll see typeof
in action using examples of each of the five primitive data types.
Numbers
The simplest number is an integer. If you assign 1 to a variable and then use the typeof operator, it will return the string "number". In the following example you can also see that the second time we set a variable's value, we don't need the var statement.
Numbers can also be floating point (decimals):
You can call typeof directly on the value, without assigning it to a variable first:
Octal and Hexadecimal Numbers
When a number starts with a 0, it's considered an octal number. For example, the octal 0377 is the decimal 255.
The last line in the example above prints the decimal representation of the octal value. While you may not be very familiar with octal numbers, you've probably used hexadecimal values to define, for example, colors in CSS stylesheets.
In CSS, you have several options to define a color, two of them being:
- Using decimal values to specify the amount of R (red), G (green) and B (blue) ranging from 0 to 255. For example
rgb(0, 0, 0)
is black andrgb(255, 0, 0)
is red (maximum amount of red and no green or blue). - Using hexadecimals, specifying two characters for each R, G and B. For example,
#000000
is black and#ff0000
is red. This is becauseff
is the hexadecimal for 255.
In JavaScript, you put 0x
before a hexadecimal value (also called hex for short).