Monday, 19 August 2013

JavaScript Data Types.

Learning JavaScript is not a bad idea as this language is the future or both web and windows applications. Lets start by looking at the data types in a nutshell.

JavaScript has the following data types:

1. Numbers
2. Strings
3. Boolean
4. Arrays
5. Object
6. null
7. undefined

Lets talk about them briefly.

1. Numbers - There is only one number type, i.e there is no separate integer, float etc.
This number is a 64-bit floating point. Which is also called IEEE-754(aka "Double").

There is a special value called NaN(Not a Number)
a. It is a result of undefined or erroneous operation. e.g divide something by zero results in NaN.
b. Toxic: any arithmetic operation with NAN as input will result NaN as output.
c. NaN is not equal to anything including NaN. i.e NaN ==NaN is false NaN is not lesser or greater then NaN :). Even when NaN is not a number but its data type is a Number.

Functions to convert string into numbers.
  •  Number(value):
It converts the value into a number.
It results NaN if it has a problem.
Similar to '+' prefix operator

  • parseInt(value, 10) e.g parseInt("55", 10)
  • + prefix operator. e.g +"55"

2. Strings: It is a sequence of  0 or more 16-bit characters.
There is no separate Character type. i.e characters are represented as strings with length 1.
Strings are Immutable.
Similar Strings are equal ( == )
String literal can use single or double quotes.
String is a object and it has lot of methods to perform on strings i.e
a. charAt
b. concat
c. match ....etc

3. Boolean:  There are two values true or false.
There is a Boolean function i.e Boolean(value) which returns true if the value is truthy and false if its falsy
It is similar to !! prefix operator.

Falsy values:
  • false
  • null
  • undefined
  • "" (empty string)
  • 0
  • NaN
Truthy Values: All other values including objects are truthy. "0" ,"false" are also truthy. They are strings.

4. null - A value that isn't anything.

5. undefined :
a.  It is the default value for a variable. i.e if you declare a variable but don't initialize it. Then its value will be undefined.

6. Object: 
  1. Its a unification of objects and hash-table.
  2. new object() produces an empty container of  name-value pairs.
  3. A name can be any string, and a value can be any value except undefined
  4. Members can be accessed with dot notation. 
  5. An object is delimited by curly braces. Inside these braces we define the object's properties in the form of key value pairs.
Object is defined like:
var person={firstname:"Jai", lastname:"Pandit", id:5566};
or
var person = new object()
// now add properties to the object.
person.firstname = "Jai"
person.lastname = "Pandit"
person.id = "5566"

7. Arrays :

The following code creates an Array called cars:
var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";
or (condensed array):
var cars=new Array("Saab","Volvo","BMW");

No comments:

Post a Comment