Interesting Javascript Facts

Wishes to the web development world :)
In the past 2 to 3 months I had chance to know about loads & loads of innovative JS Libraries
All of them made me wonder "Is there a thing that we can't do in JS?"
I wish to share some facts which got me mad in to this language & very beginnerish ;)

What is {} + []?
As soon as I saw this question my reply was "[object Object]"
But the real answer was 0 :O
Couldn't get any good guess on this, so posted @stackoverflow
And I myself couldn't believe I missed it :P
{} => Empty Block Scope & +[] => 0
So, cometh thy answer :)
Some more of the same kind
{} + {} = NaN
[] + [] = ""
[] + {} = "[object Object]"

Why obj === +obj?
I found this @ the source of Backbone.js
I was wondering why should they check JS number type in such a way?
Once again I got back to Stackoverflow
The reply once again stunned me up :D
It was to save the network bandwidth of end user :)
After compressing the code:
typeof(obj)=='number' [24 bytes]
obj===+obj [13 bytes]
So, 11 Bytes saved :D

So why is this $.each("Boolean Number String Function Array Date RegExp Object".split(" "), function () {})
This one is from jQuery :)
The moment I saw this as a javascript kid
Why not ["Boolean", "Number", "String", "Function", "Array", "Date", "RegExp", "Object"] this???
But this time I didn't seek Stackoverflow's help :P
After Compressing the code:
["Boolean","Number","String","Function","Array","Date","RegExp","Object"] (74 Bytes)
"Boolean Number String Function Array Date RegExp Object".split(" ") (69 Bytes)
So we saved 5 Bytes :)

And Finally one Crockford fact:
The guy who renamed logical && and || meaningfully :P
Because both the logical operators doesn't knock you back with the boolean result of the evaluation
Instead
&& => Guard Operator
Reason:
Statement: expr1 && expr2
Return Val: expr1 if expr1 evaluates to false else expr2
Ex:
     var a = 1 && 10, b, c = b && a ;
     console.log(a); // Will be 10 rather true
     console.log(c); // Will be undefined rather false
|| => Default Operator
Reason:
Statement: expr1 || expr2
Return val: expr1 if expr1 evaluates to true else expr2
Ex:
     var a = 10 || 1, b, c = b || a ;
     console.log(a); // Will be 10 rather true
     console.log(c); // Will be 10 rather true

Default Operator is most widely used to handle browser level inconsistencies like
evt = event || window.event;
src  = evt.target || evt.srcElement;

Also the Guard Operator
body = document && document.body; //If document exists return document body
complexBody = document && (document.body || document.getElementsByTagName(body)[0]) //Using both guard and default

Enjoy Javascript :) It has the most crazy useful parts than anyother language does :D

Comments

Popular posts from this blog

Headless Chrome/Firefox Selenium Java in Amazon EC2

Cassandra PHPCassa & Composite Types

Selenium Webdriver in Nodejs + Javascript