Thursday, November 17, 2011

A Javascript Introduction

Had a chance to read a nice javascript tutorial on variables and data types :)
Let's share :)

Q: How will I declare a variable?
var variablename;

Q: I don't like variablename I wish to have $$$$$, Is it possible?
A: Ya you can there is no restriction on varible names except
1. It should start with either a alphabet or $ or _
2. It should not use any reserve words like function, break, var, etc.,
3. It should not use any of the operators [!@#%^&*()-+=]

Q: Is there any javascript practise to declare variables?
A: The answers is upto you. But most common practise is using CamelCase [Inherited from java]
 var testvariable;
 function testFunction() {
 testObject = new Object();
Another way is Hungarian Notation - appending type of the field/variable to its name
var intAge = 19; //Interger
var strName = "xxxx"; //String
var bSet = false; //Boolean
var fpRate = 12.22; //Floating Point
var fMember = true; //Flag
Following such conventions would increase the readability factor of the code.

Q: What are the primitive types available?
A: numeric, string, boolean are the 3 primitive types available in JavaScript.
All these 3 Primitive types are wrapped by in-built Number, String and Boolean objects

Q: Wrapped by - means?
A: Number, String and Boolean are in-built objects, that support predefined methods for its instances.
Applying such methods over primitive types will also work, though they are not an instance of any of the above mentioned in-built objects.

Q: How is it possible?
A: On applying those methods over primitive types an anonymous instance of respective in-buit object is created and destroyed once the process is completed
var age = 12;
var hexAge = age.toString(16);
Here, a Number object is created and it wraps primitive type of 'age', then toString is applied. Once the result is assigned, the instance created is destroyed

Q: What about case sensitiveness?
A: Javascript is Case Sensitive
var age = 12;
var Age = 22; //Valid and Different from age

Q: What is this var? Why not int, float, String?
A: Javascript supports loose typing. Type of the variable is defined based on its content
var age; //Type undefined
var intAge = 12;  //Type numeric
var fpAge = 12.12; //Type numeric
var bAge = true; //Type boolean
var strAge = '12'; //Type string
var arMarks = new Array() //Type Array object
intAge = true; //Changes type to boolean
Every Un Initialized variable either declared or not will be initialized with undefined;
Every variable has a boolean value associated with it, to mention whether it is set or not

Q: How does String work?
A: Strings are array of characters quoted either using '' or "" [Either make no difference].
var strName = 'xxxx'; //valid
var strCity = "zz";  //valid
var strHobby = "I'm writing a blog"; //valid
var strMe = 'This is my number "12345"'; //valid
var strIV = 'I'm single'//Invalid
var strValid = 'I\'m single' //valid
Escaping characters is allowed and meaning is the same as other languages
Ex: \n, \t, \\, \'

Q: Guess the value of vars
var a = 1+2+3+'4';
var b = '4'+3+2+1;
A: a = 64 & b = 4321
+ -> Means Concatenation over strings and Addition over numerics
This is the only operator which converts numeric to string implicitly
Others convert the other way round

Q: Guess the value of vars
var a =  12/'4';
var b = '12'/'4';
var c = '12' > '4';
var d = '12' > 4;
A: a = 3 , b = 3 , c = false & d = true
Reason for c:
Both the operands are string so, it is equal to strcmp

Q: Guess the value of vars
var test = new Array('1',{"sample":'2'},'3',4,5,1.2,3.4);
var a =  test[0];
var b = test[1].sample;
var c = test[7];
var d = test['element'];
A: a = '1' ,b = 2 & c = undefined & d =undefined
Array in javascript itself is an in-built object. It is just a heterogenous collection.
It is always a hash where key for the hash is the index
So referencing an outof bound index [7] or not even an index ['element'] will never throw an error instead returns undefined

Some Typeconversion Facts
    Any arithmetic expression does implicit conversion [except + as mentioned earlier]
null---------Nan or 0 [Browser Dependent]
string-------corresponding value 
    + operator
object------[ObjectType object]
number------false if value is 0 or NAN, true other wise
string------true if not empty [empty is not equal to null]

What ever might be the type while outputting to the browser everything is converted to string :)

If we use some undeclared variable a prototype chain is followed to figure out its value.
var test = {
      'testFunc':function sampleFunc(){}

Chain:test->object [object is parent of all & end of prototype chain]

Here object test has its own prototype. On executing test.hai JS engine checks for hai in test's prototype. If not defined, it follows the prototype chain of test which is followed by object. If it couldn't find it in it's prototype it returns undefined instead any error.

You cannot access undefined of undefined, Means
var hai;
var sample = hai.test;//Invalid Will throw Type Error since base is undefined; // Invalid Will throw Referrence Error. Since bar is not even declared

Try all these yourself
false == 'false'
false == null
false == ''
false == undefined
false == 0
false == Nan
false == 'false'
true == 'true'
true == '1'
false == '0'
And wonder :)

I hope I'm Done :)