
- 13 students
- 4 lessons
- 0 quizzes
- 10 week duration
-
Javascript Objects
JavaScript Datatypes
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(" "); x=Number(x); document.write( x + x); document.write(" "); x=String(x); document.write( x + x); document.write(" "); x=Boolean(0); document.write( x); document.write(" "); }
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(" "); x=Number(x); document.write( typeof x); document.write(" "); x=String(x); document.write( typeof x); document.write(" "); x=Boolean(x); document.write( typeof x); document.write(" "); x=f1; document.write( typeof x); document.write(" "); document.write( typeof y); document.write(" "); document.write( typeof null); document.write(" "); document.write( typeof new Date()); document.write(" "); document.write( typeof [1,2]); document.write(" "); document.write( typeof {}); document.write(" "); }
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 "); else document.write("Defined "); var y=10; if(typeof( y)=="undefined") document.write("Not defined "); else document.write("Defined "); }
output
Not defined
Defined