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
- Undefined—when you try to access a variable that doesn't exist, you get the special value
- Null—this is another special data type that can have only one value, the
nullvalue. It means no value, an empty value, nothing. The difference with
undefinedis that if a variable has a value
null, it is still defined, it only happens that its value is nothing. You'll see some examples shortly.
- 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.
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 and
rgb(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,
#000000is black and
#ff0000is red. This is because
ffis the hexadecimal for 255.
0x before a hexadecimal value (also called hex for short).