What are the data types in Java Script and what are the type conversion and type checking functions?

Java Script has 5 different data types that can hold data. These are.

string, number, boolean, object, and function

The objects are of types Object, Date, Array, String, Number, and Boolean

We also have two types undefined and null that cannot hold values.

Here is a simple program that illustrates a few type conversion.


function f1()
{
var x="10";
document.write( x + x);
document.write("<br/>");
x=Number(x);
document.write( x + x);
document.write("<br/>");
x=String(x);
document.write( x + x);
document.write("<br/>");
x=Boolean(0);
document.write( x);
document.write("<br/>");
}

 

The output

1010
20
1010
false

The first line prints 1010 because x is a string

The next prints 20 because x is an integer.

I changed it back to string and we get 1010 back.

the last line prints true because we converted to boolean and every non zero value is true as per JavaScript.

 

the typeof operator is used in detecting data types of variables.


function f1()
{
var x="10";
document.write( typeof x);
document.write("<br/>");
x=Number(x);
document.write( typeof x);
document.write("<br/>");
x=String(x);
document.write( typeof x);
document.write("<br/>");
x=Boolean(x);
document.write( typeof x);
document.write("<br/>");
x=f1;
document.write( typeof x);
document.write("<br/>");
document.write( typeof y);
document.write("<br/>");
document.write( typeof null);
document.write("<br/>");
document.write( typeof new Date());
document.write("<br/>");
document.write( typeof [1,2]);
document.write("<br/>");
document.write( typeof {});
document.write("<br/>");
}

Output

string
number
string
boolean
function
undefined
object
object
object
object

Undefined variables have the data type undefined , null, date, arrays and objects {} are of the data type objects.

Simple program to check for undefined variables.


function f1()
{
if(typeof( y)=="undefined")
document.write("Not defined<br/>");
else
document.write("Defined<br/>");
var y=10;
if(typeof( y)=="undefined")
document.write("Not defined<br/>");
else
document.write("Defined<br/>");
}

output

Not defined
Defined

 

Leave a Reply