JavaScript : Some Basic Facts

Objects in JavaScript

There are three basic datatypes in JS :  Number , Boolean and String

typeof  is a function which can be used to identify the underlying object type

[code]

var x = new String("Hello");
alert (typeof(x)); // will return Object
alert( x instanceof String); // will return true
[/code]

 

[code]

var x = new Boolean(true);
alert (typeof(x)); // will return Object
alert( x instanceof Boolean); // will return true

[/code]

 

[code]

var x = new Number(5);

alert (typeof(x)); // will return Object

alert( x instanceof Number); // will return true

[/code]

 

[code]

var x = new Object("Hello");

alert (typeof(x)); // will return Object

alert( x instanceof String); // will return true

[/code]

The Other complicated Objects in JS are Object, Function and Array

Undefined vs null

In JS, undefined is a situation where no value is assigned to the variable.  Though a variable can be explicitly set to null in JS, by default if no value is assigned, it will known as undefined variable.

[code]

var x ;
alert(x); // will display "undefined"
x = null;
alert(x); // will display "null"

[/code]

Infinity and NaN

JS behaves bit differently when dealing with “Division By Zero” . In certain programming languages “Division by Zero” returns NaN. In JS, it returns Infinity. NaN is to represent “Not a Number” and it is returned when JS receives a non-number when it is expecting a Number.

[code]

var x = 10;
var y = x / 0;
if (y == "NaN") {
alert( "NAN");
} else if (y== "Infinity") {
alert ("Infinity");  // System will alert Infinity
} else {
alert (y);
}

[/code]

ParseInt is a function in JS to convert a String to Number Object. However it will return NaN if it is not able to convert it to Number. However parseInt will behave weirdly if a non-numeric string starts with a Number

[code]</pre>
ar x = "abc";
alert (parseInt(x)); // will print NaN
x = "123";
z = parseInt(x);
alert (z + ", " + typeof z); // will print 123, Number
x = "3qwe";
z = parseInt(x);
alert (z + ", " + typeof z); // will print 3 and Number
<pre>[/code]

Posted in: Programming

Leave a Comment