Showing posts with label JavaScript Data Types. Show all posts
Showing posts with label JavaScript Data Types. Show all posts

Monday, August 27, 2012

JavaScript Data Types

String, Number, Boolean, Array, Object, Null, Undefined.

JavaScript String

A string is a variable which stores a series of characters like "John Doe".

A string can be any text inside quotes. You can use simple or double quotes:

var carname="Volvo XC60";
var carname='Volvo XC60';

You can use quotes inside a string as long as they don't match the quotes surrounding the string:

var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';

Or you can put quotes inside a string by using the \ escape character:

var answer='It\'s alright';

JavaScript Number

JavaScript has only one type of number.

Numbers can be with or without decimals:

var pi=3.14;
var x=34;

The maximum number of decimals is 17.

Extra large or extra small numbers can be written with scientific notation:

var y=123e5;    // 12300000
var z=123e-5;   // 0.00123

JavaScript Boolean

Booleans can have only two values: true or false.

var x=true
var y=false

JavaScript Array

The following code creates an Array object called myCars:

var cars=new Array();

or (condensed array):

var cars=new Array("Saab","Volvo","BMW");

or (literal array):

var cars=["Saab","Volvo","BMW"];

JavaScript Object

An object is delimited by curly braces. Inside the braces the object's properties are defined as name and value pairs (name : value). The properties are separated by commas:

var person={firstname:"John", lastname:"Doe", id:5566};

The object (person) in the example above has 3 properties: fistname, lastname, and id.
Spaces and line breaks are not important:

var person={
firstname : "John",
lastname  : "Doe",
id        :  5566

You can address the object properties in two ways:


Null or Undefined

Non-existing is the value of a variable with no value.

Variables can be emptied by setting the value to null;


Declaring Variable Types

When you declare a new variable, you can declare its type using the "new" keyword:

var carname=new String;
var x=      new Number;
var y=      new Boolean;
var cars=   new Array;
var person= new Object;

lampAll variables in JavaScript are objects. When you declare a variable you create a new object.