Saturday, June 28, 2014

Primitive data types of JavaScript

JavaScript is a loosely typed language so you can use a variable without declaring it. JavaScript determines the type based on the value contained in the variable.
JavaScript supports primitive data types along with objects. The simple/primitives types in JavaScript are number, string, boolean, null and undefiend. Everything except these are objects. Before starting on primitive data type; let's understand one of the important operator, typeof.

typeof operator : This operator returns data type of an argument as string.  This can be very helpful in determining the type. The return value of this operator for primitives could be - number, string, boolean or undefined. Apart from this everything else is of type object; so arrays are objects, functions are objects, and of course objects are objects.

Now, we are armed to start on data types in detail:

 Number

JavaScript uses number type to represent floating point numbers as well as integers. So 1 and 1.0 both are same value and of same type. It gets internally represented as 64-bit floating point (same as Java's double). This saves you from type errors because all you need to know about a number is that it is a number. It supports octal (starting with 0) and hex or hexadecimal number (starting with 0x) as well. Below screenshot shows some of the common operations on numbers.


String

In JavaScript, string is sequence of characters placed between either single quote or double quote. All characters are 16 bit wide. It doesn't support character type; so to represent character, make a string with just a single character. Strings in JavaScript are immutable; so once a string is created it can never be changed. It supports attributes and methods as well (just like normal objects).


Boolean

Boolean supports only two values true and false (without quotes). The operator typeof returns "boolean" if the value is either true or false. Boolean is also immutable and has methods just like numbers and strings

Undefined

When you declare a variable but don't initialize it then JavaScript will initialize it behind the scene for you with the value as undefined.

Null

Special data type which can have only one value i.e. null. It means no value. So if a variable has null value; it's still defined (contrary to undefined).


No comments:

Post a Comment