Sunday, January 3, 2016

JavaScript Types



JavaScript has 6 basic data types per ECMAScript 5.1. These data types can be categorized into 2 groups: primitive value and object.

The six basic data types are:
0. Primitive values

Primitive values work like in any other programming languages: they are immutable (can't be changed) and can only store one value at any given time.

JavaScript only supports one type of Number: floating-point (other mainstream programming languages support integer, float, and double at least). 

Number has 3 extra special members: Infinity, -Infinity, NaN (Not a Number). 

In order to test positive and negative Infinity, a built-in Number.MAX_VALUE and Number.MIN_VALUE should be used. Anything greater than Number.MAX_VALUE is considered positive infinity while anything less than Number.MIN_VALUE is considered negative infinity

For example:
var positiveInfinity = Infinity;
if(Number.MAX_VALUE < positiveInfinity){
  console.log('Positive Infinity');
}

var negativeInfinity = -Infinity;
if(Number.MIN_VALUE > negativeInfinity){
  console.log('Negative Infinity');
}

Verifying that a number is NaN is slightly simpler: use the built-in Number.isNan() method.

2. Boolean

Boolean has exactly 2 values: true or false.

3. String

String represent text. JavaScript supports double (e.g.: "This is a string") and single quotes (e.g.: 'This is also a valid string') to denotes a string literal. String contains a series of characters in which each character is of 16-bit unsigned integer values (hence JavaScript string supports UTF-16).

NOTE: The common practice is to use single quote whenever possible.

4. Undefined

Undefined has exactly one value: undefined. Undefined is not the same with Null. Undefined refers to a state in which a variable is not even declared (i.e.: can't find where the variable has been declared with "var" keyword anywhere in your script).

5. Null

Null has exactly one value: null. Null is not the same with Undefined. Null refers to a state in which variable is declared (i.e.: var x;) but not initialized to a value (or initialized to null).

6. Object

Object in JavaScript is a collection of properties. By comparison with other mainstream programming languages, JavaScript object is more like a Dictionary or a Hash table or an Associative Array.

A function is a special type of Object that can be called and executed. Function contains additional property that act as a marker for the JavaScript interpreter to denote that this particular object is of a function.

No comments:

Post a Comment