Tuesday, November 6, 2012

JavaScript Aptitude Test- primitive types


Here are few examples related with primitive type(taken from one of the presentation by Siarhei Barysiuk). It will help us to understand types and their behavior in javascript.

number-
var n1 = 1;
alert(typeof n1);  //number

var n2 = 1.5;
alert(typeof n2);  //number

var n3 = 0100;
alert(typeof n3);  //number
alert(n3);         //64

var n4 = 0xFF;
alert(typeof n4);  //number
alert(n4);         //255

var n5 = 1e1;
alert(typeof n5);  //number
alert(n5);   //10

var n6 = 2e+3;
alert(typeof n6);  //number
alert(n6);   //2000

var n7 = 2e-3;
alert(typeof n7);  //number
alert(n7);   //0.002

var n8 = Infinity;
alert(typeof n8);  //number
alert(n8);   //Infinity

var n9 = 1e309;
alert(typeof n9);  //number
alert(n9);   //Infinity

var n10 = 6/0;
alert(typeof n10); //number
alert(n10);   //Infinity

var n11 = -1*Infinity;
alert(typeof n11); //number
alert(n11);   //-Infinity

var n12 = NaN;
alert(typeof n12); //number
alert(n12);   //NaN

var n13 = 10 * "string";
alert(typeof n13); //number
alert(n13);   //NaN

var n14 = 1 + 1 + NaN;
alert(typeof n14); //number
alert(n14);   //NaN

string-
var s1 = "some string";
alert(typeof s1);  //string

var s2 = 'a';
alert(typeof s2);  //string

var s3 = "10";
alert(typeof s3);  //string

var s41 = "one";
var s42 = "two"
var s43 = s41 + s42;
alert(s43);   //onetwo
var s51 = "10";
alert(typeof s51); //string

var s52 = s51 * 5;
alert(s52);   //50
alert(typeof s52); //number

var s6 = "1";
alert(typeof s6);  //string
alert(++s6);   //2
alert(typeof s6);  //number

var s7 = "some string 1";
var s71 = s7 * 1;
alert(typeof s7);  //string
alert(s71);   //NaN
alert(typeof s71); //number

boolean-
var b1 = false;
alert(typeof b1);  //boolean
var b2 = "some string";
var b21 = !b2;
var b22 = !!b2;
alert(typeof b2);  //string
alert(b21);   //false
alert(typeof b21); //boolean
alert(b22);   //true
alert(typeof b22); //boolean

All values become true when converted to a boolean, with the exception of the six falsy values
var b31 = "";
var b32 = null;
var b33 = false;
var b34 = NaN;
var b35 = undefined;
var b36 = 0;

null-
var nl1 = null;
alert(typeof nl1); //object
alert(nl1);   //null
var nl2 = 1 + null;
alert(nl2);   //1
var nl3 = 1*null;
alert(nl3);   //0

var u2 = 1 + undefined;
alert(u2);   //NaN

var u3 = 1 * undefined;
alert(u3);   //NaN

Arrays-
var a = [1,2,3];
alert(typeof a);   //object
alert(a);   //[1,2,3]
alert(a[0]);   //1
alert(a[5]);   //undefined
a[5] = "some string";
alert(a);   //[1,2,3,undefined,undefined,"some string"]
delete a[2];
alert(a);   //[1,2,undefined,undefined,undefined,"some string"]
delete a[5];
alert(a);   //[1,2,3,undefined,undefined,undefined]

var a2 = [[1,2,3],["string1","string2",3]];
alert(a2[0]);   //[1,2,3]
alert(a2[1]);   //["string1","string2",3]
var a3 = "one";
alert(typeof a3);  //string
alert(a3[0]);   //o
alert(typeof a3[0]);//string
alert(a3[1]);    //n

No comments:

Post a Comment