Primitive Data Types, Variables, and Operators in Object-Oriented JavaScript

Exclusive offer: get 50% off this eBook here
Object-Oriented JavaScript

Object-Oriented JavaScript — Save 50%

Create scalable, reusable high-quality JavaScript applications and libraries

$23.99    $12.00
by Stoyan Stefanov | May 2009 | AJAX Web Development

In this article by Stoyan Stefanov, you will learn about primitive data types, variables, and operators in Object-Oriented JavaScript.

Let's get started.

Variables

Variables are used to store data. When writing programs, it is convenient to use variables instead of the actual data, as it's much easier to write pi instead of 3.141592653589793 especially when it happens several times inside your program. The data stored in a variable can be changed after it was initially assigned, hence the name "variable". Variables are also useful for storing data that is unknown to the programmer when the code is written, such as the result of later operations.

There are two steps required in order to use a variable. You need to:

  • Declare the variable
  • Initialize it, that is, give it a value

In order to declare a variable, you use the var statement, like this:

var a;
var thisIsAVariable;
var _and_this_too;
var mix12three;

For the names of the variables, you can use any combination of letters, numbers, and the underscore character. However, you can't start with a number, which means that this is invalid:

var 2three4five;

To initialize a variable means to give it a value for the first (initial) time. You have two ways to do so:

  • Declare the variable first, then initialize it, or
  • Declare and initialize with a single statement

An example of the latter is:

var a = 1;

Now the variable named a contains the value 1.

You can declare (and optionally initialize) several variables with a single var statement; just separate the declarations with a comma:

var v1, v2, v3 = 'hello', v4 = 4, v5;

Variables are Case Sensitive

Variable names are case-sensitive. You can verify this statement using the Firebug console. Try typing this, pressing Enter after each line:

var case_matters = 'lower';
var CASE_MATTERS = 'upper';
case_matters
CASE_MATTERS

To save keystrokes, when you enter the third line, you can only type ca and press the Tab key. The console will auto-complete the variable name to case_matters. Similarly, for the last line—type CA and press Tab. The end result is shown on the following figure.

Object-Oriented JavaScript

Throughout the rest of this article series, only the code for the examples will be given, instead of a screenshot:

>>> var case_matters = 'lower';
>>> var CASE_MATTERS = 'upper';
>>> case_matters
"lower"
>>> CASE_MATTERS
"upper"

The three consecutive greater-than signs (>>>) show the code that you type, the rest is the result, as printed in the console. Again, remember that when you see such code examples, you're strongly encouraged to type in the code yourself and experiment tweaking it a little here and there, so that you get a better feeling of how it works exactly.

Operators

Operators take one or two values (or variables), perform an operation, and return a value. Let's check out a simple example of using an operator, just to clarify the terminology.

>>> 1 + 2
3

In this code:

  • + is the operator
  • The operation is addition
  • The input values are 1 and 2 (the input values are also called operands)
  • The result value is 3

Instead of using the values 1 and 2 directly in the operation, you can use variables. You can also use a variable to store the result of the operation, as the following example demonstrates:

>>> var a = 1;
>>> var b = 2;
>>> a + 1
2
>>> b + 2
4
>>> a + b
3
>>> var c = a + b;
>>> c
3

The following table lists the basic arithmetic operators:

Operator symbol

Operation

Example

+

Addition

>>> 1 + 2

3

-

Subtraction

>>> 99.99 - 11

88.99

*

Multiplication

>>> 2 * 3

6

/

Division

>>> 6 / 4

1.5

%

Modulo, the reminder of a division

>>> 6 % 3

0

>>> 5 % 3

2

It's sometimes useful to test if a number is even or odd. Using the modulo operator it's easy. All odd numbers will return 1 when divided by 2, while all even numbers will return 0.

>>> 4 % 2

0

>>> 5 % 2

1

++

Increment a value by 1

Post-increment is when the input value is incremented after it's returned.

>>> var a = 123; var b = a++;

>>> b

123

>>> a

124

The opposite is pre-increment; the input value is first incremented by 1 and then returned.

>>> var a = 123; var b = ++a;

>>> b

124

>>> a

124

--

Decrement a value by 1

Post-decrement

>>> var a = 123; var b = a--;

>>> b

123

>>> a

122

Pre-decrement

>>> var a = 123; var b = --a;

>>> b

122

>>> a

122

When you type var a = 1; this is also an operation; it's the simple assignment operation and = is the simple assignment operator.

There is also a family of operators that are a combination of an assignment and an arithmetic operator. These are called compound operators. They can make your code more compact. Let's see some of them with examples.

>>> var a = 5;
>>> a += 3;
8

In this example a += 3; is just a shorter way of doing a = a + 3;

>>> a -= 3;
5

Here a -= 3; is the same as a = a - 3;

Similarly:

>>> a *= 2;
10
>>> a /= 5;
2
>>> a %= 2;
0

In addition to the arithmetic and assignment operators discussed above, there are other types of operators, as you'll see later in this article series.

 

Primitive Data Types

Any value that you use is of a certain type. In JavaScript, there are the following primitive data types:

  1. Number—this includes floating point numbers as well as integers, for example 1, 100, 3.14.
  2. String—any number of characters, for example "a", "one", "one 2 three".
  3. Boolean—can be either true or false.
  4. 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 value undefined.
  5. 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 with undefined is 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.

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. The data types 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"

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.

>>> 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 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, #000000 is black and #ff0000 is red. This is because ff 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

Exponent Literals

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.

Object-Oriented JavaScript

>>> 2e-3
0.002
>>> 123.456E-3
0.123456
>>> typeof 2e-3
"number"

Infinity

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

NaN

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
Object-Oriented JavaScript Create scalable, reusable high-quality JavaScript applications and libraries
Published: July 2008
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

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 article.

String Conversions

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()):

>>> 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"

Special Strings

Some strings that have a special meaning, as listed in the following table:

String

Meaning

Example

 

 

'

"

is the escape character.

When you want to have quotes inside your string, you escape them, so that JavaScript doesn't think they mean the end of the string.

If you want to have an actual backslash in the string, escape it with another backslash.

>>> var s = 'I don't know';

This is an error, because JavaScript thinks the string is "I don" and the rest is invalid code. The following are valid:

>>> var s = 'I don't know';

>>> var s = "I don't know";

>>> var s = "I don't know";

>>> var s = '"Hello", he said.';

>>> var s = ""Hello", he said.";

Escaping the escape:

>>> var s = "12"; s;

"12"

n

End of line

>>> var s = 'n1n2n3n';

>>> s

"

1

2

3

"

r

Carriage return

All these:

>>> var s = '1r2';

>>> var s = '1nr2';

>>> var s = '1rn2';

Result in:

>>> s

"1

2"

t

Tab

>>> var s = "1t2"

>>> s

"1 2"

u

u followed by a character code allows you to use Unicode

Here's my name in Bulgarian written with Cyrillic characters:

>>> "u0421u0442u043Eu044Fu043D"

"Стoян"

There are some additional characters which are rarely used: b (backspace), v (vertical tab), and f (form feed).

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"

Logical Operators

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:

Operation

Result

true && true

true

true && false

false

false && true

false

false && false

false

true || true

true

true || false

true

false || true

true

false || false

false

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

Operator Precedence

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

Best Practice: Use parentheses instead of relying on operator precedence. This makes your code easier to read and understand.

Lazy Evaluation

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.

Comparison

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.

Operator symbol

Description

Example

==

Equality comparison:

Returns true when both operands are equal. The operands are converted to the same type before being compared.

>>> 1 == 1

true

>>> 1 == 2

false

>>> 1 == '1'

true

===

Equality and type comparison:

Returns true if both operands are equal and of the same type. It's generally better and safer if you compare this way, because there's no behind-the-scenes type conversions.

>>> 1 === '1'

false

>>> 1 === 1

true

!=

Non-equality comparison:

Returns true if the operands are not equal to each other (after a type conversion)

>>> 1 != 1

false

>>> 1 != '1'

false

>>> 1 != '2'

true

!==

Non-equality comparison without type conversion:

Returns true if the operands are not equal OR they are different types.

>>> 1 !== 1

false

>>> 1 !== '1'

true

Returns true if the left operand is greater than the right one.

>>> 1 > 1

false

>>> 33 > 22

true

>=

Returns true if the left operand is greater than or equal to the right one.

>>> 1 >= 1

true

Returns true if the left operand is less than the right one.

>>> 1 < 1

false

>>> 1 < 2

true

<=

Returns true if the left operand is less than or equal to the right one.

>>> 1 <= 1

true

>>> 1 <= 2

true

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"

Summary

Let's quickly summarize what has been discussed so far:

  • There are five primitive data types in JavaScript:
    1. number
    2. string
    3. boolean
    4. undefined
    5. null
  • Everything that is not a primitive is an object
  • The number data type can store positive and negative integers or floats, hexadecimal numbers, octal numbers, exponents, and the special numbers NaN, Infinity, and –Infinity
  • The string data type contains characters in quotes
  • The only values of the boolean data type are true and false
  • The only value of the null data type is the value null
  • The only value of the undefined data type is the value undefined
  • All values become true when converted to a boolean, with the exception of the six falsy values:
    1. ""
    2. null
    3. undefined
    4. 0
    5. NaN
    6. false
  • The various other operators are:

    1. Arithmetic operators: +, -, *, /, and %.
    2. Increment operators: ++ and --.
    3. Assignment operators: =, +=, -=, *=, /=, and %=.
    4. Special operators: typeof and delete.
    5. Logical operators: &&, ||, and !.
    6. Comparison operators: ==, ===, !=, !==, <, >, >=, and <=.
Object-Oriented JavaScript Create scalable, reusable high-quality JavaScript applications and libraries
Published: July 2008
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Stoyan Stefanov

Stoyan Stefanov is a Facebook engineer, author, and speaker. He talks regularly about web development topics at conferences and his blog www.phpied.com, and also runs a number of other sites, including JSPatterns.com—a site dedicated to exploring JavaScript patterns. Previously at Yahoo!, Stoyan was the architect of YSlow 2.0 and creator of the image optimization tool Smush.it.

A "citizen of the world", Stoyan was born and raised in Bulgaria, but is also a Canadian citizen, currently residing in Los Angeles, California. In his offline moments, he enjoys playing the guitar, taking flying lessons, and spending time at the Santa Monica beaches with his family.

Books From Packt


PHP and script.aculo.us Web 2.0 Application Interfaces
PHP and script.aculo.us Web 2.0 Application Interfaces

Drupal 6 JavaScript and jQuery
Drupal 6 JavaScript and jQuery

Learning jQuery 1.3
Learning jQuery 1.3

JBoss Tools 3 Developers Guide
JBoss Tools 3 Developers Guide

WordPress Plugin Development: Beginner's Guide
WordPress Plugin Development: Beginner's Guide

Apache MyFaces Trinidad 1.2: A Practical Guide
Apache MyFaces Trinidad 1.2: A Practical Guide

Grails 1.1 Web Application Development
Grails 1.1 Web Application Development

Seam 2.x Web Development
Seam 2.x Web Development


No votes yet
var mynumber = mynumber || 10; by
1) this is only dangerous for primitive data types, because generally with objects null and undefined will have the same meaning of "no value". (this is why most people don't know the difference between them :)) 2) do you have the "var" in this example? This would have a strange side-effect if mynumber is undefined on the local scope but is defined in the global...

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
x
t
h
N
5
1
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software