Types

Data Types

There are 4 primitive data types and 2 reference types in JavaScript.

  • Primitive types: Undefined, Boolean, Number, String.
  • Reference types: Object and Function.

A variable of type Object holds a reference to an unordered list of key-value pairs. These are similar to the dictionary type in Python and the Map types in Java.  A variable of type Function holds a reference to a function.

The typeof Operator

You can determine the current type of a variable using the typeof operator, which returns one of the following strings: “undefined”, “Boolean”, “string”, “number”, “object”, “function”.

var message = “hi”;
console.log(typeof message);      // prints ”string”

The Undefined Type

A variable that has not been declared has the type Undefined.  For example, below we pass a variable that was not declared to the log function.

console.log(typeof y);     // prints the type: “undefined”

A variable that has been declared but has not been initialized also has the type Undefined.

var x;                     // x is declared but not initialized.
console.log(typeof x);     // prints the type: “undefined”

Declared variables of type Undefined (ie. uninitialized) have the value – undefined.

var x;
console.log(x);     //  prints the value: “undefined”

A variable that has not been declared does not have the value undefined. Referencing an undeclared variable will cause an error except in the case when using the typeof operator.

console.log(y);    // error - putting this in your code will break your script

The Number Type

We can initialize variables using any of the following values.

var intNum = 2;
var octalNum = 070;    // octal for 56, preface number with 0, can’t use in strict mode
var hex = 0xA;         // hex for 10, preface number with 0x
var float = 0.5;       // need decimal point, converted to int if possible
var efloat = 3.12e3;   // 3.12 x 10^3

Comparison of arithmetic expressions using floats should be avoided as arithmetic on floats produces approximations.

For example, the sum 0.1 + 0.2 equals 0.30000000000000004.  In the following example, the value in sum is compared to the value 0.3.  Since they are not equal the console.log() statement is never executed.

var sum = 0.1 + 0.2;
if (sum == 0.3) {            // evaluates to false
    console.log("equal"); 
}

Range of Values

Number.MIN_VALUE and Number.MAX_VALUE are constants that hold the smallest and largest values for the Number type.

If a computation produces a value that cannot be represented between these bounds it is given the value Infinity or –Infinity. These values can also be accessed as Number.NEGATIVE_INFINITY and Number.POSITIVE_INFINITY.

NaN

NaN (Not a Number) is the value that is used when a computation is executed but cannot complete like dividing 0 by 0.

NaN is not equal to any value (including NaN) using == comparison.

JavaScript provides isNaN( ) to check if a value equals NaN. isNaN() returns true if the argument cannot be converted to a Number (e.g. strings and NaN), otherwise returns false.

var myNum = 0 / 0;
if (isNaN(myNum)) {
    console.log(“myNum is NaN”);
}

var name = "Joe";
if (isNaN(name)) { 
    console.log(“name is NaN”); 
}

Number Conversions

There are 3 functions to convert nonnumeric values to numbers.

Number() takes any value as an argument and returns NaN or a number according to the following.

Argument Return Value
Boolean type true returns 1, false return 0
Number type The same number
null 0
Undefined type NaN
Strings containing only numbers optionally with + or – its integer value
String containing valid floating point format its float value
String containing valid hex format its hex value
Empty string 0
Any other string NaN
**** Object type valueOf() and the above rules are applied to the result.  If equal to NaN the toString() and the rules for converting strings is applied.

The functions parseInt() and parseFloat() are better when trying to parse integer and float strings.  parseInt() returns NaN for empty string unlike Number() which returns 0.  If the first char is a number, + or -, then it converts the chars until the first nonnumeric char is found.  For example,

if (1234 == parseInt(”1234blue”)) {     // evaluates to true
    console.log(“true”);
}

Similarly, parseInt(“22.5”) returns the value 22.

The String Type

The String type represents a sequence of 0 or more 16-bit Unicode characters. They can be delineated by either double quotes or single quotes.

var firstName = “Joe”;
var lastName = ‘Black’;

Strings are immutable, that is, once initialized, they cannot be changed. To change a string the previous value is destroyed.

Escape Sequences

Strings can contain the following escape sequences.

Escape Sequence Meaning
\n new line
\t tab
\\ backslash (\)
\’ single quote (‘)
\” double quote (“)
\unnnn A Unicode character represented by the hexadecimal value nnnn

We can also use Unicode characters.

var sigma = “\u03a3”;

Converting Values to String

The toString() method can be called on any variable with a type Number, Boolean, Object, or String.

var age = 20;
console.log(age.toString());

When called on a Number, the string returned is by default base 10 unless a radix is passed to toString().

If the value of the variable is null or undefined, null or undefined is returned respectively.

The Null Value

A variable that has a null value has the type Object. It’s equivalent to setting the variable equal to a null pointer (0).

var x = null;
console.log(typeof x);   // prints “object”

Since we should always initialize variables, if the variable will be used later to reference an Object then we should initialize it to null as shown above.

The Boolean Type

The Boolean type has two values: true and false.

Any variable’s value can be cast to a Boolean using the Boolean( ) function.

Data Type Values converted to true Values converted to false
Boolean true false
String Any nonempty string “”
Number Any nonzero number 0 or NaN
Object Any nonnull object null
Undefined undefined

Where a Boolean expression is expected, types are automatically converted to Boolean. For example,

var message = “Hi”;
if (message) {
    console.log(message);
}