- Object/Oriented JavaScript
- Stoyan Stefanov
- 2707字
- 2021-08-13 19:25:52
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.
Any value that doesn't belong to one of the five primitive types listed above is an object. Even 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.
>>> var n = 1; >>> typeof n;
"number"
>>> n = 1234; >>> typeof n;
"number"
Numbers can also be floating point (decimals):
>>> var n2 = 1.23; >>> typeof n;
"number"
You can call typeof
directly on the value, without assigning it to a variable first:
>>> typeof 123;
"number"
When a number starts with a 0, it's considered an octal number. For example, the octal 0377
is the decimal 255.
>>> var n3 = 0377; >>> typeof n3;
"number"
>>> n3;
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).
>>> var n4 = 0x00; >>> typeof n4;
"number"
>>> n4;
0
>>> var n5 = 0xff; >>> typeof n5;
"number"
>>> n5;
255
1e1
(can also be written as 1e+1
or 1E1
or 1E+1)
represents the number one with one zero after it, or in other words 10. Similarly, 2e+3
means the number 2 with 3 zeros after it, or 2000.
>>> 1e1
10
>>> 1e+1
10
>>> 2e+3
2000
>>> typeof 2e+3;
"number"
2e+3
means moving the decimal point 3 digits to the right of the number 2. There's also 2e-3
meaning you move the decimal point 3 digits to the left of the number 2.

>>> 2e-3
0.002
>>> 123.456E-3
0.123456
>>> typeof 2e-3
"number"
There is a special value in JavaScript called Infinity
. It represents a number too big for JavaScript to handle. Infinity
is indeed a number, as typing typeof Infinity
in the console will confirm. You can also quickly check that a number with 308 zeros is ok, but 309 zeros is too much. To be precise, the biggest number JavaScript can handle is 1.7976931348623157e+308
while the smallest is 5e-324
.
>>> Infinity
Infinity
>>> typeof Infinity
"number"
>>> 1e309
Infinity
>>> 1e308
1e+308
Dividing by 0 will give you infinity.
>>> var a = 6 / 0; >>> a
Infinity
Infinity is the biggest number (or rather a little bigger than the biggest), but how about the smallest? It's infinity with a minus sign in front of it, minus infinity.
>>> var i = -Infinity; >>> i
-Infinity
>>> typeof i
"number"
Does this mean you can have something that's exactly twice as big as Infinity
—from 0 up to infinity and then from 0 down to minus infinity? Well, this is purely for amusement and there's no practical value to it. When you sum infinity and minus infinity, you don't get 0, but something that is called NaN (Not A Number).
>>> Infinity - Infinity
NaN
>>> -Infinity + Infinity
NaN
Any other arithmetic operation with Infinity
as one of the operands will give you Infinity
:
>>> Infinity - 20
Infinity
>>> -Infinity * 3
-Infinity
>>> Infinity / 2
Infinity
>>> Infinity - 99999999999999999
Infinity
What was this NaN you saw in the example above? It turns out that despite its name, "Not A Number", NaN is a special value that is also a number.
>>> typeof NaN
"number"
>>> var a = NaN; >>> a
NaN
You get NaN when you try to perform an operation that assumes numbers but the operation fails. For example, if you try to multiply 10
by the character "f"
, the result is NaN, because "f"
is obviously not a valid operand for a multiplication.
>>> var a = 10 * "f"; >>> a
NaN
NaN is contagious, so if you have even only one NaN in your arithmetic operation, the whole result goes down the drain.
>>> 1 + 2 + NaN
NaN
Strings
A string is a sequence of characters used to represent text. In JavaScript, any value placed between single or double quotes is considered a string. This means that 1 is a number but "1" is a string. When used on strings, typeof
returns the string "string".
>>> var s = "some characters"; >>> typeof s;
"string"
>>> var s = 'some characters and numbers 123 5.87'; >>> typeof s;
"string"
Here's an example of a number used in string context:
>>> var s = '1'; >>> typeof s;
"string"
If you put nothing in quotes, it's still a string (an empty string):
>>> var s = ""; typeof s;
"string"
As you saw before, when you use the plus sign with two numbers, this is the arithmetic operation addition. However, if you use the plus sign on strings, this is a string concatenation operation and it returns the two strings glued together.
>>> var s1 = "one"; var s2 = "two"; var s = s1 + s2; s;
"onetwo"
>>> typeof s;
"string"
The dual function of the +
operator can be a source of errors. Therefore, it is always best to make sure that all of the operands are strings if you intend to concatenate them, and are all numbers if you intend to add them. You will learn various ways to do so further in the chapter and the book.
When you use a number-like string as an operand in an arithmetic operation, the string is converted to a number behind the scenes. (This works for all operations except addition, because of addition's ambiguity)
>>> var s = '1'; s = 3 * s; typeof s;
"number"
>>> s
3
>>> var s = '1'; s++; typeof s;
"number"
>>> s
2
A lazy way to convert any number-like string to a number is to multiply it by 1 (a better way is to use a function called parseInt()
, as you'll see in the next chapter):
>>> var s = "100"; typeof s;
"string"
>>> s = s * 1;
100
>>> typeof s;
"number"
If the conversion fails, you'll get NaN
:
>>> var d = '101 dalmatians'; >>> d * 1
NaN
A lazy way to convert anything to a string is to concatenate it with an empty string.
>>> var n = 1; >>> typeof n;
"number"
>>> n = "" + n;
"1"
>>> typeof n;
"string"
Booleans
There are only two values that belong to the boolean data type: the values true
and false
, used without quotes.
>>> var b = true; typeof b;
"boolean"
>>> var b = false; typeof b;
"boolean"
If you quote true
or false
, they become strings.
>>> var b = "true"; typeof b;
"string"
There are three operators, called logical operators, that work with boolean values. These are:
!
—logical NOT (negation)&&
—logical AND||
—logical OR
In everyday meaning, if something is not true, it is false. Here's the same statement expressed using JavaScript and the logical !
operator.
>>> var b = !true; >>> b;
false
If you use the logical NOT twice, you get the original value:
>>> var b = !!true; >>> b;
true
If you use a logical operator on a non-boolean value, the value is converted to boolean behind the scenes.
>>> var b = "one"; >>> !b;
false
In the case above, the string value "one"
was converted to a boolean true
and then negated. The result of negating true
is false
. In the next example, we negate twice so the result is true
.
>>> var b = "one"; >>> !!b;
true
Using double negation is an easy way to convert any value to its boolean equivalent. This is rarely useful, but on the other hand understanding how any value converts to a boolean is important. Most values convert to true
with the exception of the following (which convert to false)
:
- The empty string ""
null
undefined
- The number 0
- The number
NaN
- The boolean
false
These six values are sometimes referred to as being falsy, while all others are truthy (including, for example, the strings "0", " ", and "false").
Let's see some examples of the other two operators—the logical AND and the logical OR. When you use AND, the result is true
only if all of the operands are true
. When using OR, the result is true
if at least one of the operands is true
.
>>> var b1 = true; var b2 = false; >>> b1 || b2
true
>>> b1 && b2
false
Here's a table that lists the possible operations and their results:

You can use several logical operations one after the other:
>>> true && true && false && true
false
>>> false || true || false
true
You can also mix &&
and ||
in the same expression. In this case, you should use parentheses to clarify how you intend the operation to work. Consider these:
>>> false && false || true && true
true
>>> false && (false || true) && true
false
You might wonder why the expression above (false && false
||
true && true
) returned true
. The answer lies in operator precedence. As you know from mathematics:
>>> 1 + 2 * 3
7
This is because multiplication has precedence over addition, so 2
*
3
is evaluated first, as if you've typed:
>>> 1 + (2 * 3)
7
Similarly for logical operations, !
has the highest precedence and is executed first, assuming there are no parentheses that demand otherwise. Then, in the order of precedence, comes &&
and finally ||
. In other words:
>>> false && false || true && true
true
is the same as:
>>> (false && false) || (true && true)
true
If you have several logical operations one after the other, but the result becomes clear at some point before the end, the final operations will not be performed, because they can't affect the end result. Consider this:
>>> true || false || true || false || true
true
Since these are all OR operations and have the same precedence, the result will be true
if at least one of the operands is true
. After the first operand is evaluated, it becomes clear that the result will be true
, no matter what values follow. So the JavaScript engine decides to be lazy (ok, efficient) and not do unnecessary work by evaluating code that doesn't affect the end result. You can verify this behavior by experimenting in the console:
>>> var b = 5; >>> true || (b = 6)
true
>>> b
5
>>> true && (b = 6)
6
>>> b
6
This example also shows another interesting behavior—if JavaScript encounters a non-boolean expression as an operand in a logical operation, the non-boolean is returned as a result.
>>> true || "something"
true
>>> true && "something"
"something"
This behavior is something to watch out for and avoid, because it makes the code harder to understand. Sometimes you might see this behavior being used to define variables when you're not sure whether they were previously defined. In the next example, if the variable v
is defined, its value is kept; otherwise, it's initialized with the value 10
.
var mynumber = mynumber || 10;
This is simple and looks elegant, but be aware that it is not completely bulletproof. If mynumber
is defined and initialized to 0 (or to any of the six falsy values), this code might not behave in exactly the way it was designed to work.
There's another set of operators that all return a boolean value as a result of the operation. These are the comparison operators. The following table lists them, together with some examples.



An interesting thing to note is that NaN
is not equal to anything, not even itself.
>>> NaN == NaN
false
Undefined and null
You get the undefined
value when you try to use a variable that doesn't exist, or one that hasn't yet been assigned a value. When you declare a variable without initializing it, JavaScript automatically initializes it to the value undefined
.
If you try using a non-existing variable, you'll get an error message.
>>> foo
foo is not defined
If you use the typeof
operator on a non-existing variable, you get the string "undefined".
>>> typeof foo
"undefined"
If you declare a variable without giving it a value, you won't get an error when you use that variable. But the typeof
still returns "undefined".
>>> var somevar; >>> somevar >>> typeof somevar
"undefined"
The null
value, on the other hand, is not assigned by JavaScript behind the scenes; it can only be assigned by your code.
>>> var somevar = null
null
>>> somevar
null
>>> typeof somevar
"object"
Although the difference between null
and undefined
is small, it may be important at times. For example, if you attempt an arithmetic operation, you can get different results:
>>> var i = 1 + undefined; i;
NaN
>>> var i = 1 + null; i;
1
This is because of the different ways null
and undefined
are converted to the other primitive types. Below are examples that show the possible conversions.
Conversion to a number:
>>> 1*undefined
NaN
>>> 1*null
0
Conversion to a boolean:
>>> !!undefined
false
>>> !!null
false
Conversion to a string:
>>> "" + null
"null"
>>> "" + undefined
"undefined"
- PPT設計實用教程
- Solid Works 2021產品設計標準教程
- AutoCAD Civil 3D 2018 場地設計實例教程
- CorelDRAW服裝設計實用教程(第四版)
- Photoshop影視動漫角色繪制技法精解
- 中文版3ds Max 2016實用教程
- Photoshop CC UI設計標準培訓教程
- 用Cubase輕松制作你的短視頻音樂
- ASP.NET 3.5 Social Networking
- 虛擬現實:沉浸于VR夢境
- 攝影師的后期必修課(調色篇)
- 中文版Photoshop CC基礎教程
- After Effects 2023實訓教程
- 中文版CorelDRAW X7技術大全
- Joomla! 1.5 Content Administration