SlideShare a Scribd company logo
1 of 33
Download to read offline
JavaScript WTF Master Class!
WTF #1 – Optional Semi-Colons (Auto-magic semicolons [ASI])
This was my first real “we’re not in Kansas anymore” kind ofmomentwith JavaScript as I hadn’trealised thatit was
ok to leave out semi-colons and have the interpreter try and figure out where the end of statements are based on line
breaks.That is,I can write;
// either
var a = 101;
var b = 201;
// or
var c = 301
var
d
= 401
alert(a + b + c + d);
It appears thatthere are a bunch of rules (and,clearly, a bunch of edge cases) to remember ifyou want to go with the
idea of leaving out semi-colons and relying on white-space so Iguess whatI draw from this is that I’d always put
explicit semi-colons everywhere myself.The one that I particularlythoughtI would fall foul of would be;
function square(x) {
return
x * x
}
alert(square(10))
which is a very different function from;
function square(x) {
return x * x
}
alert(square(10))
purely because ofthe whitespace and so I guess the only way I’m going to feel safe is;
function square(x) {
return (x * x);
}
alert(square(10));
Reference: Flanagan, “JavaScript The Definitive Guide”, Page 25
First of all you should know which statements are affected by the automatic semicolon insertion (also known as ASI
for brevity):
 empty statement
 var statement
 expression statement
 do-while statement
 continue statement
 break statement
 return statement
 throw statement
WTF #2 – JavaScript and Underflow, Overflow, Div Zero
This was a real surprise to me.In JavaScript;
var x = 100 / 0;
alert(x);
provides a value of Infinity rather than any kind of error or exception although if we divide 0 by 0;
var x = 0 / 0;
alert(x);
then we get NaN rather than an infinite value. It feels like the functions isNan() and isFinite() are massive helpers
here in trying to determine whether you’ve got a decentvalue or not to work with.
Reference: Flanagan, “JavaScript The Definitive Guide”, Page 33
WTF #3 – Truthy and Falsy
It sounds a little like “itchy and scratchy”. Coming straightfrom C# you have very fixed ideas abouthow you can
make use of bool values in that you can assign them literal values;
1. bool b = true;
and you can assign them the results ofexpressions thatresolve to booleans;
1. int i = 22;
2.
3. bool b = (i == 0);
but you can’tdo what you could do in C++ and use FALSE as a pseudonym for zero and any other values as a
pseudonym for non-zero so in C# you can’tdo something like;
1. object reference = null;
2.
3. if (reference) // no-no in C#
4. {
5.
6. }
There isn’tthat conversion from non-boolean types to booleans.The JavaScript version of this story feels like “C++
and then some” in that you have the situation where everything is true unless it’s one of;
undefined, null, 0, –0, Nan, “”
you can definitely feel where this is coming from butI think it’s going to take a little getting used to for me and,
especially,when you get into the various rules via which JavaScript is prepared to do conversions from one type to
another
Reference: Flanagan, “JavaScript The Definitive Guide”, Page 40
'' == '0' // false
The left hand side is an empty string, and the right hand side is a string with one character. They are
false because it is making a comparison between two un identical strings.
0 == '' // true
Hence, why this one is true, because 0 is falsy and the empty string is falsy.
0 == '0' // true
This one is a bit trickier. If you do !!'0' you get true, so the string is definitely truthy. However,
using == doesn't check types, only values, and 0 can be a String and a Number. In this case,0's
value is equal to '0's value. This occurs by coercing the String to Number.
false == undefined // false
The value undefined is special in JavaScript and is not equal to anything else except null.
However, it is falsy.
false == null // false
Again, null is special. It is only equal to undefined. It is also falsy.
null == undefined // true
null and undefined are similar, but not the same. null means nothing, whilst undefined is the
value for a variable not set or not existing. It would kind of make sense that their values would be
considered equal.
If you want to be really confused, check this...
'nrt' == 0
A string consisting only of whitespace is considered equal to 0.
WTF #4 – The Global Object
You’ll think I’m an idiot (fair comment ) but I’d no idea that when I was working with JavaScript and defining global
variables and global functions and so on that I was actuallymutating the global object.I’d never appreciated that
there was a global objectand so I’d been living in a place of ignorance and so now I know (or at leastI think I do) that
when I’m writing;
var myVariable = "some value";
// this
console.log(myVariable);
// is just like this
console.log(this.myVariable);
// is just like this
console.log(this["myVariable"]);
// and this is true
console.log("myVariable" in this);
then I’ve more of an appreciation that whatI’m doing is adding to the properties ofthe global objectwhich I can reach
via its this reference.
Reference: Flanagan, “JavaScript The Definitive Guide”, Page 42
WTF #5 – “Expando Objects”
JavaScript has the very powerful/scarysystem which allows you to justexpand objects with new properties as/when
you feel like it unless those objects have been marked to disallow it.So, I can justgo ahead and make myselfa new
objectand then start to add things to it;
var myObject = {};
// just add whatever I want to this thing...
myObject.x = 10;
myObject.y = 20;
myObject.add = function () { return (this.x + this.y); }
console.log(myObject.add());
// arrays are also objects
var myArray = [1, 2, 3];
myArray.sum = function () {
// no attempt to require numbers here.
var sum = 0;
for (var i = 0; i < this.length; i++) {
sum += this[i];
}
return (sum);
};
console.log(myArray.sum());
// functions are also objects
var square = function (x) {
return (x * x);
};
square.y = 100;
console.log(square.y + square(5));
This is all a little bit mind-blowing and it’s hard to think of anything similar in the .NET world although there are
ExpandoObjecttypes that mightget you somewhere near to it and especiallywhen coupled with dynamic in C# 5;
1. dynamic expando = new ExpandoObject();
2. expando.x = 10;
3. expando.y = 10;
4. expando.Add = new Func<int>(() => expando.x + expando.y);
5. Console.WriteLine(expando.Add());
6.
7. // can't really do the array/function variant in the same spirit
8. // I don't think...
I suspectthatthis will take a little getting used to
Reference: Flanagan, “JavaScript The Definitive Guide”
WTF #6 – Wrappers
Wrapper objects feel a little to me like the process of“boxing” in .NET. In an ideal world,it’d be nice to treat
everything in an object-oriented language as an object but it’s impractical to do so for primitive types generally
because your performance goes straightoutof the window and so languages come up with this idea of object-when-
needs-to-be like .NEThas with boxing. In JavaScript, this seems to called “Wrapper Objects” and it allows me to treat
a primitive like an objectwhen I want to.
// pure primitives
var n = 1;
var s = "this is a string";
var b = false;
console.log(typeof (n)); // number
console.log(typeof (s)); // string
console.log(typeof (b)); // boolean
// wrapped primitives
var nW = new Number(1);
var sW = new String("this is a string");
var bW = new Boolean(false);
console.log(typeof (nW)); // object
console.log(typeof (sW)); // object
console.log(typeof (bW)); // object
console.log(n == nW); // true
console.log(s == sW); // true
console.log(b == bW); // true
console.log(n === nW); // false
console.log(s === sW); // false
console.log(b === bW); // false
and I guess this doesn’treallyseem thatdifferentfrom the C# world;
1. // string omitted because it's a ref type in .NET
2. int n = 1;
3. bool b = false;
4.
5. Console.WriteLine(n.GetType());
6. Console.WriteLine(b.GetType());
7.
8. object nW = n;
9. object nB = b;
10.
11. Console.WriteLine(nW.GetType()); // .NET still says int
12. Console.WriteLine(nB.GetType()); // .NET still says bool
13.
14. // .NET requires the explicit cast to the primitive type
15. Console.WriteLine(n == (int)nW);
16. Console.WriteLine(b == (bool)nB);
although that shortsample does alreadyhighlightdifferences and,combined with WTF 5 above about “Expando
Objects” I was particularlystruck by the example given in Flanagan around;
var myNumber = 1;
myNumber.myProperty = "ABC"; // "box" the primitive once.
console.log(myNumber.myProperty); // "box" again, different wrapper, undefined
Reference: Flanagan, “JavaScript The Definitive Guide”, Page 43
WTF #7 – Type Conversions
Generally speaking,Ihate type conversions much as Ihate precedence rules I can never learn tables containing
rules so for me an ideal programming language would be one thatmade everything explicit so I never had to learn
any conversion rules or precedence rules – I’m notsaying that I’m typical here
JavaScript has a pretty complexlist of type conversions thatit’s prepared to bring into play on your behalf.Most of
them I found pretty intuitive. The way I decided whether they were intuitive or not run down the conversion table with
my finger over the results and see if I could just“guess” how itwould work.
Here’s the ones that I got wrong and/or found a bit trickier to guess;
var minusZero = new String(-0);
console.log(minusZero); // logs 0, not -0
var undefinedNumber = new Number(undefined);
console.log(undefinedNumber); // logs NaN
var numbers = new Number([1]);
console.log(numbers); // this logs 1, not so surprising
numbers = new Number([1,2,3]);
console.log(numbers); // this logs NaN, a little surprising
but others did seem largelyto do whatI’d expect them to do with the possible caveatthat I’d have to remember;
var b = false;
var o = new Boolean(b);
if (o)
{
console.log("a little unexpected but, true");
}
Reference: Flanagan, “JavaScript The Definitive Guide”, Page 46/49.
WTF#8 – Object to Primitive Conversions
Types and Primitives
To understand this,you'll need to understand the difference between primitive and non-primitive values in
JavaScript. There are 5 primitive types, which are associated with the various primitive values.
 Null: The value null.
 Undefined: The value undefined.
 Number: All numbers,such as 0 and 3.14. Also NaN, and Infinity.
 Boolean: The values true and false.
 String: All strings,such as "foo" and "".
All other values are non-primitive,including arrays,functions,and plain old objects.For completeness,here are the
results ofthe typeof operator,applied to these values:
typeof null; // "object"
typeof undefined; // "undefined"
typeof 0; // "number" (`typeof NaN` is also "number")
typeof true; // "boolean"
typeof "foo"; // "string"
typeof {}; // "object"
typeof function () { }; // "function"
typeof []; // "object"
This feels like a bit of a minefield.Objects convert to booleans very naturally by converting to true for every value
that’s not null or undefined so that’s easyenough to “get”.
Converting objects to strings seems simple in thatit seems to go via toString() and then if that isn’tappropriate (i.e.
doesn’tgive some primitive value that can be converted to a string or doesn’texist) then it goes via valueOf() to try
and get to some primitive value;
var o = { x:10 };
o.toString = function()
{
return("ToString Value is " + this.x);
}
// logs "ToString Value is x"
console.log(o);
// break toString by having it return a non-primitive
o.toString = function()
{
return(this);
}
o.valueOf = function()
{
return("ValueOf Value is " + this.x);
}
// logs "ValueOf Value is x"
console.log(o);
and so that seems relativelysimple as does the conversion to a number which sortof goes the other way around;
var o = { x:10 };
o.valueOf = function()
{
return(this.x);
}
// logs this.x ( 10 ) via valueOf
console.log(Number(o));
// take valueOf away
delete o.valueOf;
o.toString = function()
{
return(String(this.x));
};
// allow toString to kick in
// logs "10" via toString
console.log(Number(o));
but then there appears to be some built-in behaviours to certain operators (e.g.+) which have their own way of
working – need to do a little more digging to understand thatfully.
Reference: Flanagan, “JavaScript The Definitive Guide”, Page 50/51.
var foo = {
toString: function () {
return 5;
},
valueOf: function () {
return "foo";
}
};
alert(foo.toString() + 1); // 6 (bad!)
alert(foo + 1); // "foo1" (no good!)
alert(+foo); // NaN (the worst!)
WTF #9 – Variable Scope and Hoisting
It was a bit of a surprise to find that JavaScript didn’tsupportthe notion of local scope blocks as in;
function foo()
{
var x = 10;
{
var y = 10;
}
// surprised to find that y still exists here.
console.log(y);
}
foo();
but it’s pretty clearly stated but it was more of a shock to realise thatthis ultimatelymeans thatyou can use variables
before you appear to have declared them
var globalVar = "Four";
function foo()
{
// we set the local variable we didn't declare yet :-S
globalVar = "One";
// "One"
console.log(globalVar);
// we declare the local variable seemingly after it's
// already been used :-S The function will only be
// called now though.
var func= function()
{
console.log("Two");
return("Three");
}
var globalVar = func();
// "Three"
console.log(globalVar);
}
foo();
// "Four"
console.log(globalVar);
That, definitely, will take a little bit of getting used to
Reference: Flanagan, “JavaScript The Definitive Guide”, Page 54.
It turns out that it doesn’tmatter whether the line that contains the declaration would ever be executed.
The following two functions are equivalent:
function foo() {
if (false) {
var x = 1;
}
return;
var y = 1;
}
function foo() {
var x, y;
if (false) {
x = 1;
}
return;
y = 1;
}
function test() {
foo(); // TypeError "foo is not a function"
bar(); // "this will run!"
var foo = function () { // function expression assigned to local variable 'foo'
alert("this won't run!");
}
function bar() { // function declaration, given the name 'bar'
alert("this will run!");
}
}
test();
(function(){
alert(window); // "undefined"
var window = window;
})();
WTF #10 – Equality and Strict Equality
I’ll nominate myselfagain for being ignorantofthe fact that there are 2 ways to check equality in JavaScript. There’s
the regular “==” and then there’s the “===” and I hadn’tappreciated thatthey existed (along with “!=” and “!==”).
Of the two, I think I prefer === or the “strictequality operator” because,for me, it starts from the strong place of “if two
values are of different types then they are not equal” I play around with this and come up with no surprises;
var n = 1;
var s = "1";
var s2= "1";
var o = { x : 1 };
var o2 = { x: 1 };
o.valueOf = o2.valueOf = function() { return(this.x); }
var a = [1];
var a2 = [1];
var b = true;
// different type so not equal. nice. clear. good.
console.log(n === s);
console.log(n === o);
console.log(n === a);
console.log(n === b);
console.log(s === o);
console.log(s === a);
console.log(s === b);
console.log(o === b);
console.log(o === a);
console.log(a === b);
// different object so not equal.
console.log(o === o2);
// nothing is equal to null
console.log(o === null);
// except null
var nu = null;
console.log(nu === null);
// nothing is equal to undefined
console.log(o === undefined);
// except undefined
var un;
console.log(un === undefined);
// nothing is equal to NaN, not even NaN :-)
var na = NaN;
console.log(na === NaN);
// o is equal to itself
console.log(o === o);
// but not o2
console.log(o === o2);
// s is equal to s2
console.log(s === s2);
// a is not equal to a2
console.log(a === a2);
when I move to the “not so strict” equality operator it all gets a bit more “gray” because there’s a whole tonne of
conversions thatthe operator is prepared to try out on my behalf;
var n = 1;
var s = "1";
var b = true;
var o = { x: 1 };
o.valueOf = function() { return(this.x); }
var p = { x: 1 };
p.toString = function() { return(this.x + 1); }
// true. convert s to a number.
console.log(n == s);
// true. convert bool to 1.
console.log(b == n);
// true. use valueOf on o to turn it into a number.
console.log(o == n);
// true. convert b to 1, convert o to 1.
console.log(o == b);
// true. use toString on p to turn it into a string.
console.log(p == "2");
but I think it’s all pretty understandable although Iguess the most“impressive” for me is that one of;
var b = true;
var o = {x : 1};
o.toString = function() { return("01"); }
console.log(b == o);
where if I interpretbehvaviour correctly, the boolean is converted to a number and then the object is converted to a
number and then they are equal
Reference: Flanagan, “JavaScript The Definitive Guide”, Page 71.
WTF #11 – Magic of Short-Circuiting ANDs and Truthy/Falsy
I really like this one. I find in a language like C# it can be quite painful to index into a complex objectmodel while all
the time trying to protect yourselffrom the pains ofa null reference exception. The magic of the AND operator
returning the rightvalue at the right time looks to make this a lot easier in JavaScript which I really rather like;
"use strict";
var policy =
{
holder:
{
firstName: "Fred",
lastName: "Smith",
age: 45
}
};
// like this :-)
var age = policy && policy.holder && policy.holder.age;
console.log(age);
Reference: Flanagan, “JavaScript The Definitive Guide”, Page 123.
WTF#12 – Function Arguments
I think it was C# 4.0 that finally got around to the notion of optional and named arguments to a function whereas
JavaScript is way ahead with the sortof zany stuff that you get to do when writing a function.
"use strict";
function f (a, b, c)
{
console.log("Arg a present " + (a !== undefined));
console.log("Arg b present " + (b !== undefined));
console.log("Arg c present " + (c !== undefined));
if (arguments.length > 3)
{
for (var i = 3; i < arguments.length; i++)
{
console.log("Extra argument " + arguments[i]);
}
}
}
// too few args leaves b,c undefined.
f(10);
// too many args is not a problem.
f(10,20,30,40,50);
Reference: Flanagan, “JavaScript The Definitive Guide”, Page 171-173.
WTF #13 – Nested Functions
I really like the very natural way that I can define functions inside offunctions in JavaScriptand, optionally, form
closures over the local variable state.
"use strict";
function moduloCounter(modulo) {
// only way to get back to this variable will be via functions
// I return keeping it out of anything publicly accessible.
var counter = 0;
return (
{
inc: function () {
counter++;
if (!(counter - modulo)) {
counter = 0;
}
return (counter);
},
dec: function () {
counter--;
if (counter < 0) {
counter = (modulo - 1);
}
return (counter);
},
valueOf: function () {
return (counter);
}
}
);
}
var module8 = moduloCounter(8);
for (var i = 0; i < 16; i++) {
console.log(module8.inc());
}
for (var i = 0; i < 16; i++) {
console.log(module8.dec());
}
That’s pretty clever stuff although it takes a bit of getting used to and it feels that this sortof technique has a lot of
power to it.
Reference: Flanagan, “JavaScript The Definitive Guide”, Page 166.
WTF #14 – Arrays versus Lists
Arrays seem fairlyeasy to get to grips with in JavaScript but there’s a few differences to whatyou’d see in .NET that
leads to the JavaScript array feeling more like .NET’s ArrayList in many ways. One is around the idea that I can just
add things to an array whenever and wherever I feel like it;
var myArray = [1, 2, 3];
myArray.push(4);
console.log(myArray); // 1,2,3,4
var last = myArray.pop();
console.log(myArray); // 1,2,3
myArray.unshift(0);
console.log(myArray); // 0,1,2,3
var first = myArray.shift();
console.log(myArray); // 1,2,3
myArray[99] = 'mixed content';
console.log(myArray.length); // 100
console.log(myArray[98]); // undefined
console.log(98 in myArray); // false
myArray[98] = undefined;
console.log(myArray[98]); // undefined
console.log(98 in myArray); // true
// arrays are still objects of course
myArray.whatever = "anything I like";
console.log(myArray.whatever);
and there’s the difference between an array “element” being in the array and undefined versus it simplynot
being in the array which I tried to highlight.There’s also a lack of multi-dimensional arrays butthat’s not so hard to
solve with arrays of arrays.
Reference: Flanagan, “JavaScript The Definitive Guide”, Page 151,152.
WTF #15 – Function Invocation Context & Strict Mode
I find this one a bit tricky (to say the least).If I’m writing a plain old,vanilla function then the this pointer is setto the
global object? Ouch!
function foo(){
this.x = 10;
}
foo();
console.log(this.x); // 10, scary :-)
It’s “nice” to see that ES5 strict mode comes along and try to tidy this up but I don’tsuppose thatoffers much
consolation outside ofa strict environment.
"use strict";
function foo(){
this.x = 10; // TypeError: cool!
}
foo();
console.log(this.x);
I could see hours going down the drain to bugs introduced by those kinds ofproblems.
Reference: Flanagan, “JavaScript The Definitive Guide”, Page 167.
WTF #16 – Nested Functions & Invocation Context
This feels like another “gotchya” to me and combines with WTF #15 above. If I have a nested function inside a
method;
this.x = 101;
var myObject = {
x: 1,
y: 1,
myFunction: function()
{
var myNestedFunction = function()
{
return(this.x);
};
return(myNestedFunction());
}
};
console.log(myObject.myFunction());
then even it picks up the global objectfor its invocation context unless I’m in strictmode when it throws an error.
What I should be doing is picking up the this pointer myself such that the nested function captures itbut that’d be
easy to forget
"use strict";
this.x = 101;
var myObject = {
x: 1,
y: 1,
myFunction: function()
{
var self = this;
var myNestedFunction = function()
{
return(self.x);
};
return(myNestedFunction());
}
};
console.log(myObject.myFunction());
Reference: Flanagan, “JavaScript The Definitive Guide”, Page 169.
WTF #17 – Everything’s a Function
There’s a piece of code in Crockford’s book that I had to read about 5 times.He (very tersely) defines a new method
on all functions called method (this is his code below);
Function.protoype.method = function(name, func)
{
this.prototype[name] = func;
return(this);
};
because it’s altering the prototype for Function I read that as adding a method (called method) to
every Function objectand that new method knows how to add another method of a given name and implementation
to the prototype. Wow.
It’s used something like below and Ithink it’s fairly well known/understood/etc;
String.method(
'lengthSquared',
function()
{
return(this.length * this.length);
}
);
My function here makes a new lengthSquared function available on any string.
The brilliance ofthis is quite something butfor the firstfew readings ofit, I kept saying to myself;
“How can Function.protoype be used to add a method to a String when String is not a function. It’s a class or a
type butnot a function!!”
because Iwasn’tthinking like JavaScript – of course String isn’ta class or a type, it’s a function.
In fact – I think I’ll call this “Mike’s FirstLaw of JavaScript – It’s a Function, Stupid”
Reference: Crockford, “JavaScript, The Good Parts”, Page 33.
WTF #18 – parseInt() needs help
I hadn’tappreciated thatthis would happen and that, by default, the “09” would be interpreted as octal;
var myString = "09";
var myOctalInteger = this.parseInt(myString);
var myDecimalInteger = this.parseInt(myString,10);
console.log(myOctalInteger);
console.log(myDecimalInteger);
Reference: Stefanov, “JavaScript Patterns”, Page 23.
WTF #19 – There is no Integer
Numerical calculations are comparatively slow because there is no Integer type,
only Number - and Number is an IEEE floating point double-precision (64 bit) type. This
means that Number exhibits the floating point rounding error:
0.1 + 0.2 === 0.3 //false
Since there's no distinction between integers and floats, unlike C# or Java, this is true:
0.0 === 0; //true
Finally a Number puzzle. How can you achieve the following?
a === b; //true
1/a === 1/b; //false
The answer is that the specification of Number allows for both positive and negative zero
values. Positive zero equals negative zero, but positive infinity does not equal negative
infinity:
var a = 0 * 1; // This simple sum gives 0
var b = 0 * -1; // This simple sum gives -0 (you could also just
// do "b = -0" but why would you do that?)
a === b; //true: 0 equals -0
1/a === 1/b; //false: Infinity does not equal -Infinity
WTF #20 – Floating point arithmetic
This can be a major cause of frustration for people who are new to JavaScript and are trying
to perform some kind of mathematical computation.
1. <script>
2. alert(0.02 / 0.1); //0.19999999999999998
3. alert(1.14 * 100); //113.99999999999999 ;)
4. </script>
This is where the Math.round() functions come in handy
> Math.min() < Math.max()
false
This makes sense – they’re functions which normally expect arguments. Without arguments, default behaviour
is to return Infinity for Math.min() and -Infinity for Math.max(). And so Infinity < -Infinity ===
false
WTF #21 – Plus operator overloading
The plus operator stands for both arithmetic operations and also string concatenation. This
is convenient if used correctly. Let's take a look
1. var msg, one="1";
2. msg = 2 + "1"; // msg = "21"
3. msg = 2 + one; // msg = "21"
4. msg = 1 + 1 + 1 + " musketeers"; // msg = "3 musketeers"
5. msg = "Bond " + 0 + 0 + 7; //msg = "Bond 007"
6. </script>
The above behaviour is because the operations are performed left to right. If we use
parentheses the behaviour will change based on the order of the string or number in it.
Can you work out as to what the below will alert?
function foo() {
var a = "5";
var b = "4";
alert(+a + +b);
}
JavaScript is looselytyped, except in switch statements.JavaScriptis NOT looselytyped when it comes
to case comparisons.
var myVar = 5;
if (myVar == '5') { // returns true since JavaScript is loosely typed
alert("hi"); //this alert will show since JS doesn't usually care about data type.
}
switch (myVar) {
case '5':
alert("hi"); // this alert will not show since the data types don't match
}
WTF #22 – Undefined Can Be Defined
OK, let’s end with a silly, rather inconsequential one. Strange as it might sound, undefined is not
actually a reserved word in JavaScript, even though it has a special meaning and is the only way to
determine whether a variable is undefined. So:
var someVar;
alert(someVar == undefined); //evaluates true
So far, so normal. But:
undefined = "I'm not undefined!";
var someVar;
alert(someVar == undefined); //evaluates false!
WTF #23 – Misc
instances and default values
When you create instances of String or Number, they take the default value ("" for strings
and 0 for numbers). This is not the same for Object and Array.
var a = new Number;
a == 0 // true
var a = new String;
a == "" // true
var a = new Object;
a == {} // false
var a = new Array;
a == [] // false
This is even more confusing when using the JSON-style syntax to create objects and arrays.
var a = {};
a == {} // false
var a = [];
a == [] // false
boolean paradox
"0" && {} // true
0 && {} // false, ok...fair enough
0 == "0" // true, wtf!
[] == ![] // true, wtf!
coerced
Careful w/ number type coercion!
a = 012 // 10
concat coerce
"3" + 1 // '31'
"3" - 1 // 2
"222" - -"111" // "333" (⊙﹏⊙)
true has a value
(true + 1) === 2; // true
(true + true) === 2; // true
true === 2; // false
true === 1; // false
coerce equality
3 == "3" // true
null is not falsy
[] == false; // true
"" == false; // true
null == false; // false, that's more like it
null is not an object
typeof null // object
null instanceof Object // false
Classic null is not an Object.
more coerce fun
3 == "03" // true!
not a number is a number
typeof NaN // number, of course.
Now that makes sense.
References:
http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/default.aspx
http://wtfjs.com/
http://bonsaiden.github.com/JavaScript-Garden/
http://blog.boyet.com/blog/javascriptlessons/
http://appendto.com/blog/2011/05/good-javascript-habits-c-developers-elijah-manor
http://channel9.msdn.com/Events/MIX/MIX11/OPN08
http://jqfundamentals.com/book/index.html
http://osteele.com/sources/javascript/functional/
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatternsjavascript
http://robertnyman.com/category/javascript/
http://javascriptweblog.wordpress.com/
http://shichuan.github.com/javascript-patterns/
https://github.com/itpastorn/programmering-1-med-js/blob/master/javascript-quirks.markdown
Books:
JavaScript:The DefinitiveGuide by David Flanagan
Object-Oriented by Stoyan Stefanov
JavaScript:The Good Parts by Douglas Crockford
JavaScriptPatterns by Stoyan Stefanov
High Performance JavaScriptby Nicholas C.Zakas
High Performance Web Sites by Steve Souders
Eloquent JavaScriptby Marijn Haverbeke
Secrets of the JavaScriptNinja by John Resig
Advanced JavaScriptby Chuck Easttom
Head FirstJavaScriptby Michael Morrison

More Related Content

What's hot

Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsUses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsPatchSpace Ltd
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To ClosureRobert Nyman
 
Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Oky Firmansyah
 
Javascript Basics - part 1
Javascript Basics - part 1Javascript Basics - part 1
Javascript Basics - part 1Kasia Drzyzga
 
Javascript basics
Javascript basicsJavascript basics
Javascript basicsSolv AS
 
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b....NET Conf UY
 

What's hot (9)

Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsUses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & Stubs
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
Concurrency Patterns
Concurrency PatternsConcurrency Patterns
Concurrency Patterns
 
Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)
 
Javascript Basics - part 1
Javascript Basics - part 1Javascript Basics - part 1
Javascript Basics - part 1
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
Enterprise js pratices
Enterprise js praticesEnterprise js pratices
Enterprise js pratices
 
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
I just met you, and "this" is crazy, but here's my NaN, so call(me), maybe? b...
 
All of javascript
All of javascriptAll of javascript
All of javascript
 

Similar to A JavaScript Master Class - From the Wows to the WTFs

Section 8 Programming Style and Your Brain: Douglas Crockford
Section 8 Programming Style and Your Brain: Douglas CrockfordSection 8 Programming Style and Your Brain: Douglas Crockford
Section 8 Programming Style and Your Brain: Douglas Crockfordjaxconf
 
Douglas Crockford - Programming Style and Your Brain
Douglas Crockford - Programming Style and Your BrainDouglas Crockford - Programming Style and Your Brain
Douglas Crockford - Programming Style and Your BrainWeb Directions
 
Keeping Eloquent Eloquent
Keeping Eloquent EloquentKeeping Eloquent Eloquent
Keeping Eloquent EloquentColin DeCarlo
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascriptMD Sayem Ahmed
 
Learning puppet chapter 2
Learning puppet chapter 2Learning puppet chapter 2
Learning puppet chapter 2Vishal Biyani
 
Js in-ten-minutes
Js in-ten-minutesJs in-ten-minutes
Js in-ten-minutesPhong Vân
 
perl 6 hands-on tutorial
perl 6 hands-on tutorialperl 6 hands-on tutorial
perl 6 hands-on tutorialmustafa sarac
 
Hardened JavaScript
Hardened JavaScriptHardened JavaScript
Hardened JavaScriptKrisKowal2
 
Douglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsDouglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsAjax Experience 2009
 
JavaScripts internals #1
JavaScripts internals #1JavaScripts internals #1
JavaScripts internals #1Martin Pernica
 
JavaScript Best Pratices
JavaScript Best PraticesJavaScript Best Pratices
JavaScript Best PraticesChengHui Weng
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingKeshav Kumar
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingKeshav Kumar
 

Similar to A JavaScript Master Class - From the Wows to the WTFs (20)

Section 8 Programming Style and Your Brain: Douglas Crockford
Section 8 Programming Style and Your Brain: Douglas CrockfordSection 8 Programming Style and Your Brain: Douglas Crockford
Section 8 Programming Style and Your Brain: Douglas Crockford
 
Douglas Crockford - Programming Style and Your Brain
Douglas Crockford - Programming Style and Your BrainDouglas Crockford - Programming Style and Your Brain
Douglas Crockford - Programming Style and Your Brain
 
Javascript
JavascriptJavascript
Javascript
 
Keeping Eloquent Eloquent
Keeping Eloquent EloquentKeeping Eloquent Eloquent
Keeping Eloquent Eloquent
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascript
 
Learning puppet chapter 2
Learning puppet chapter 2Learning puppet chapter 2
Learning puppet chapter 2
 
Js in-ten-minutes
Js in-ten-minutesJs in-ten-minutes
Js in-ten-minutes
 
All of Javascript
All of JavascriptAll of Javascript
All of Javascript
 
JavaScript Essentials
JavaScript EssentialsJavaScript Essentials
JavaScript Essentials
 
Java script unleashed
Java script unleashedJava script unleashed
Java script unleashed
 
perl 6 hands-on tutorial
perl 6 hands-on tutorialperl 6 hands-on tutorial
perl 6 hands-on tutorial
 
Goodparts
GoodpartsGoodparts
Goodparts
 
Hardened JavaScript
Hardened JavaScriptHardened JavaScript
Hardened JavaScript
 
Douglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsDouglas Crockford Presentation Goodparts
Douglas Crockford Presentation Goodparts
 
JavaScripts internals #1
JavaScripts internals #1JavaScripts internals #1
JavaScripts internals #1
 
JavaScript Best Pratices
JavaScript Best PraticesJavaScript Best Pratices
JavaScript Best Pratices
 
Java Script Introduction
Java Script IntroductionJava Script Introduction
Java Script Introduction
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
Javascript
JavascriptJavascript
Javascript
 

More from Shahriar Hyder

Effective Communication Skills for Software Engineers
Effective Communication Skills for Software EngineersEffective Communication Skills for Software Engineers
Effective Communication Skills for Software EngineersShahriar Hyder
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion PrincipleShahriar Hyder
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design PatternShahriar Hyder
 
Taking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocketTaking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocketShahriar Hyder
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming FundamentalsShahriar Hyder
 
Object Relational Mapping with LINQ To SQL
Object Relational Mapping with LINQ To SQLObject Relational Mapping with LINQ To SQL
Object Relational Mapping with LINQ To SQLShahriar Hyder
 
C# 3.0 Language Innovations
C# 3.0 Language InnovationsC# 3.0 Language Innovations
C# 3.0 Language InnovationsShahriar Hyder
 

More from Shahriar Hyder (9)

Effective Communication Skills for Software Engineers
Effective Communication Skills for Software EngineersEffective Communication Skills for Software Engineers
Effective Communication Skills for Software Engineers
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion Principle
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Pattern
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
Taking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocketTaking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocket
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming Fundamentals
 
Object Relational Mapping with LINQ To SQL
Object Relational Mapping with LINQ To SQLObject Relational Mapping with LINQ To SQL
Object Relational Mapping with LINQ To SQL
 
C# 3.0 Language Innovations
C# 3.0 Language InnovationsC# 3.0 Language Innovations
C# 3.0 Language Innovations
 
Introduction to Linq
Introduction to LinqIntroduction to Linq
Introduction to Linq
 

Recently uploaded

The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...BookNet Canada
 

Recently uploaded (20)

The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
 

A JavaScript Master Class - From the Wows to the WTFs

  • 1. JavaScript WTF Master Class! WTF #1 – Optional Semi-Colons (Auto-magic semicolons [ASI]) This was my first real “we’re not in Kansas anymore” kind ofmomentwith JavaScript as I hadn’trealised thatit was ok to leave out semi-colons and have the interpreter try and figure out where the end of statements are based on line breaks.That is,I can write; // either var a = 101; var b = 201; // or var c = 301 var d = 401 alert(a + b + c + d); It appears thatthere are a bunch of rules (and,clearly, a bunch of edge cases) to remember ifyou want to go with the idea of leaving out semi-colons and relying on white-space so Iguess whatI draw from this is that I’d always put explicit semi-colons everywhere myself.The one that I particularlythoughtI would fall foul of would be; function square(x) { return x * x } alert(square(10)) which is a very different function from; function square(x) { return x * x } alert(square(10)) purely because ofthe whitespace and so I guess the only way I’m going to feel safe is; function square(x) { return (x * x); } alert(square(10)); Reference: Flanagan, “JavaScript The Definitive Guide”, Page 25 First of all you should know which statements are affected by the automatic semicolon insertion (also known as ASI for brevity):
  • 2.  empty statement  var statement  expression statement  do-while statement  continue statement  break statement  return statement  throw statement
  • 3. WTF #2 – JavaScript and Underflow, Overflow, Div Zero This was a real surprise to me.In JavaScript; var x = 100 / 0; alert(x); provides a value of Infinity rather than any kind of error or exception although if we divide 0 by 0; var x = 0 / 0; alert(x); then we get NaN rather than an infinite value. It feels like the functions isNan() and isFinite() are massive helpers here in trying to determine whether you’ve got a decentvalue or not to work with. Reference: Flanagan, “JavaScript The Definitive Guide”, Page 33
  • 4. WTF #3 – Truthy and Falsy It sounds a little like “itchy and scratchy”. Coming straightfrom C# you have very fixed ideas abouthow you can make use of bool values in that you can assign them literal values; 1. bool b = true; and you can assign them the results ofexpressions thatresolve to booleans; 1. int i = 22; 2. 3. bool b = (i == 0); but you can’tdo what you could do in C++ and use FALSE as a pseudonym for zero and any other values as a pseudonym for non-zero so in C# you can’tdo something like; 1. object reference = null; 2. 3. if (reference) // no-no in C# 4. { 5. 6. } There isn’tthat conversion from non-boolean types to booleans.The JavaScript version of this story feels like “C++ and then some” in that you have the situation where everything is true unless it’s one of; undefined, null, 0, –0, Nan, “” you can definitely feel where this is coming from butI think it’s going to take a little getting used to for me and, especially,when you get into the various rules via which JavaScript is prepared to do conversions from one type to another Reference: Flanagan, “JavaScript The Definitive Guide”, Page 40 '' == '0' // false The left hand side is an empty string, and the right hand side is a string with one character. They are false because it is making a comparison between two un identical strings. 0 == '' // true Hence, why this one is true, because 0 is falsy and the empty string is falsy. 0 == '0' // true This one is a bit trickier. If you do !!'0' you get true, so the string is definitely truthy. However, using == doesn't check types, only values, and 0 can be a String and a Number. In this case,0's value is equal to '0's value. This occurs by coercing the String to Number.
  • 5. false == undefined // false The value undefined is special in JavaScript and is not equal to anything else except null. However, it is falsy. false == null // false Again, null is special. It is only equal to undefined. It is also falsy. null == undefined // true null and undefined are similar, but not the same. null means nothing, whilst undefined is the value for a variable not set or not existing. It would kind of make sense that their values would be considered equal. If you want to be really confused, check this... 'nrt' == 0 A string consisting only of whitespace is considered equal to 0.
  • 6. WTF #4 – The Global Object You’ll think I’m an idiot (fair comment ) but I’d no idea that when I was working with JavaScript and defining global variables and global functions and so on that I was actuallymutating the global object.I’d never appreciated that there was a global objectand so I’d been living in a place of ignorance and so now I know (or at leastI think I do) that when I’m writing; var myVariable = "some value"; // this console.log(myVariable); // is just like this console.log(this.myVariable); // is just like this console.log(this["myVariable"]); // and this is true console.log("myVariable" in this); then I’ve more of an appreciation that whatI’m doing is adding to the properties ofthe global objectwhich I can reach via its this reference. Reference: Flanagan, “JavaScript The Definitive Guide”, Page 42
  • 7. WTF #5 – “Expando Objects” JavaScript has the very powerful/scarysystem which allows you to justexpand objects with new properties as/when you feel like it unless those objects have been marked to disallow it.So, I can justgo ahead and make myselfa new objectand then start to add things to it; var myObject = {}; // just add whatever I want to this thing... myObject.x = 10; myObject.y = 20; myObject.add = function () { return (this.x + this.y); } console.log(myObject.add()); // arrays are also objects var myArray = [1, 2, 3]; myArray.sum = function () { // no attempt to require numbers here. var sum = 0; for (var i = 0; i < this.length; i++) { sum += this[i]; } return (sum); }; console.log(myArray.sum()); // functions are also objects var square = function (x) { return (x * x); }; square.y = 100; console.log(square.y + square(5)); This is all a little bit mind-blowing and it’s hard to think of anything similar in the .NET world although there are ExpandoObjecttypes that mightget you somewhere near to it and especiallywhen coupled with dynamic in C# 5; 1. dynamic expando = new ExpandoObject(); 2. expando.x = 10; 3. expando.y = 10; 4. expando.Add = new Func<int>(() => expando.x + expando.y); 5. Console.WriteLine(expando.Add()); 6. 7. // can't really do the array/function variant in the same spirit 8. // I don't think... I suspectthatthis will take a little getting used to Reference: Flanagan, “JavaScript The Definitive Guide”
  • 8. WTF #6 – Wrappers Wrapper objects feel a little to me like the process of“boxing” in .NET. In an ideal world,it’d be nice to treat everything in an object-oriented language as an object but it’s impractical to do so for primitive types generally because your performance goes straightoutof the window and so languages come up with this idea of object-when- needs-to-be like .NEThas with boxing. In JavaScript, this seems to called “Wrapper Objects” and it allows me to treat a primitive like an objectwhen I want to. // pure primitives var n = 1; var s = "this is a string"; var b = false; console.log(typeof (n)); // number console.log(typeof (s)); // string console.log(typeof (b)); // boolean // wrapped primitives var nW = new Number(1); var sW = new String("this is a string"); var bW = new Boolean(false); console.log(typeof (nW)); // object console.log(typeof (sW)); // object console.log(typeof (bW)); // object console.log(n == nW); // true console.log(s == sW); // true console.log(b == bW); // true console.log(n === nW); // false console.log(s === sW); // false console.log(b === bW); // false and I guess this doesn’treallyseem thatdifferentfrom the C# world; 1. // string omitted because it's a ref type in .NET 2. int n = 1; 3. bool b = false; 4. 5. Console.WriteLine(n.GetType()); 6. Console.WriteLine(b.GetType()); 7. 8. object nW = n; 9. object nB = b; 10. 11. Console.WriteLine(nW.GetType()); // .NET still says int 12. Console.WriteLine(nB.GetType()); // .NET still says bool 13. 14. // .NET requires the explicit cast to the primitive type 15. Console.WriteLine(n == (int)nW); 16. Console.WriteLine(b == (bool)nB); although that shortsample does alreadyhighlightdifferences and,combined with WTF 5 above about “Expando Objects” I was particularlystruck by the example given in Flanagan around;
  • 9. var myNumber = 1; myNumber.myProperty = "ABC"; // "box" the primitive once. console.log(myNumber.myProperty); // "box" again, different wrapper, undefined Reference: Flanagan, “JavaScript The Definitive Guide”, Page 43
  • 10. WTF #7 – Type Conversions Generally speaking,Ihate type conversions much as Ihate precedence rules I can never learn tables containing rules so for me an ideal programming language would be one thatmade everything explicit so I never had to learn any conversion rules or precedence rules – I’m notsaying that I’m typical here JavaScript has a pretty complexlist of type conversions thatit’s prepared to bring into play on your behalf.Most of them I found pretty intuitive. The way I decided whether they were intuitive or not run down the conversion table with my finger over the results and see if I could just“guess” how itwould work. Here’s the ones that I got wrong and/or found a bit trickier to guess; var minusZero = new String(-0); console.log(minusZero); // logs 0, not -0 var undefinedNumber = new Number(undefined); console.log(undefinedNumber); // logs NaN var numbers = new Number([1]); console.log(numbers); // this logs 1, not so surprising numbers = new Number([1,2,3]); console.log(numbers); // this logs NaN, a little surprising but others did seem largelyto do whatI’d expect them to do with the possible caveatthat I’d have to remember; var b = false; var o = new Boolean(b); if (o) { console.log("a little unexpected but, true"); } Reference: Flanagan, “JavaScript The Definitive Guide”, Page 46/49.
  • 11. WTF#8 – Object to Primitive Conversions Types and Primitives To understand this,you'll need to understand the difference between primitive and non-primitive values in JavaScript. There are 5 primitive types, which are associated with the various primitive values.  Null: The value null.  Undefined: The value undefined.  Number: All numbers,such as 0 and 3.14. Also NaN, and Infinity.  Boolean: The values true and false.  String: All strings,such as "foo" and "". All other values are non-primitive,including arrays,functions,and plain old objects.For completeness,here are the results ofthe typeof operator,applied to these values: typeof null; // "object" typeof undefined; // "undefined" typeof 0; // "number" (`typeof NaN` is also "number") typeof true; // "boolean" typeof "foo"; // "string" typeof {}; // "object" typeof function () { }; // "function" typeof []; // "object" This feels like a bit of a minefield.Objects convert to booleans very naturally by converting to true for every value that’s not null or undefined so that’s easyenough to “get”. Converting objects to strings seems simple in thatit seems to go via toString() and then if that isn’tappropriate (i.e. doesn’tgive some primitive value that can be converted to a string or doesn’texist) then it goes via valueOf() to try and get to some primitive value; var o = { x:10 }; o.toString = function() { return("ToString Value is " + this.x); } // logs "ToString Value is x" console.log(o); // break toString by having it return a non-primitive o.toString = function() { return(this); } o.valueOf = function() { return("ValueOf Value is " + this.x); } // logs "ValueOf Value is x" console.log(o); and so that seems relativelysimple as does the conversion to a number which sortof goes the other way around;
  • 12. var o = { x:10 }; o.valueOf = function() { return(this.x); } // logs this.x ( 10 ) via valueOf console.log(Number(o)); // take valueOf away delete o.valueOf; o.toString = function() { return(String(this.x)); }; // allow toString to kick in // logs "10" via toString console.log(Number(o)); but then there appears to be some built-in behaviours to certain operators (e.g.+) which have their own way of working – need to do a little more digging to understand thatfully. Reference: Flanagan, “JavaScript The Definitive Guide”, Page 50/51. var foo = { toString: function () { return 5; }, valueOf: function () { return "foo"; } }; alert(foo.toString() + 1); // 6 (bad!) alert(foo + 1); // "foo1" (no good!) alert(+foo); // NaN (the worst!)
  • 13. WTF #9 – Variable Scope and Hoisting It was a bit of a surprise to find that JavaScript didn’tsupportthe notion of local scope blocks as in; function foo() { var x = 10; { var y = 10; } // surprised to find that y still exists here. console.log(y); } foo(); but it’s pretty clearly stated but it was more of a shock to realise thatthis ultimatelymeans thatyou can use variables before you appear to have declared them var globalVar = "Four"; function foo() { // we set the local variable we didn't declare yet :-S globalVar = "One"; // "One" console.log(globalVar); // we declare the local variable seemingly after it's // already been used :-S The function will only be // called now though. var func= function() { console.log("Two"); return("Three"); } var globalVar = func(); // "Three" console.log(globalVar); } foo(); // "Four" console.log(globalVar); That, definitely, will take a little bit of getting used to Reference: Flanagan, “JavaScript The Definitive Guide”, Page 54.
  • 14. It turns out that it doesn’tmatter whether the line that contains the declaration would ever be executed. The following two functions are equivalent: function foo() { if (false) { var x = 1; } return; var y = 1; } function foo() { var x, y; if (false) { x = 1; } return; y = 1; } function test() { foo(); // TypeError "foo is not a function" bar(); // "this will run!" var foo = function () { // function expression assigned to local variable 'foo' alert("this won't run!"); } function bar() { // function declaration, given the name 'bar' alert("this will run!"); } } test(); (function(){ alert(window); // "undefined" var window = window; })();
  • 15. WTF #10 – Equality and Strict Equality I’ll nominate myselfagain for being ignorantofthe fact that there are 2 ways to check equality in JavaScript. There’s the regular “==” and then there’s the “===” and I hadn’tappreciated thatthey existed (along with “!=” and “!==”). Of the two, I think I prefer === or the “strictequality operator” because,for me, it starts from the strong place of “if two values are of different types then they are not equal” I play around with this and come up with no surprises; var n = 1; var s = "1"; var s2= "1"; var o = { x : 1 }; var o2 = { x: 1 }; o.valueOf = o2.valueOf = function() { return(this.x); } var a = [1]; var a2 = [1]; var b = true; // different type so not equal. nice. clear. good. console.log(n === s); console.log(n === o); console.log(n === a); console.log(n === b); console.log(s === o); console.log(s === a); console.log(s === b); console.log(o === b); console.log(o === a); console.log(a === b); // different object so not equal. console.log(o === o2); // nothing is equal to null console.log(o === null); // except null var nu = null; console.log(nu === null); // nothing is equal to undefined console.log(o === undefined); // except undefined var un; console.log(un === undefined); // nothing is equal to NaN, not even NaN :-)
  • 16. var na = NaN; console.log(na === NaN); // o is equal to itself console.log(o === o); // but not o2 console.log(o === o2); // s is equal to s2 console.log(s === s2); // a is not equal to a2 console.log(a === a2); when I move to the “not so strict” equality operator it all gets a bit more “gray” because there’s a whole tonne of conversions thatthe operator is prepared to try out on my behalf; var n = 1; var s = "1"; var b = true; var o = { x: 1 }; o.valueOf = function() { return(this.x); } var p = { x: 1 }; p.toString = function() { return(this.x + 1); } // true. convert s to a number. console.log(n == s); // true. convert bool to 1. console.log(b == n); // true. use valueOf on o to turn it into a number. console.log(o == n); // true. convert b to 1, convert o to 1. console.log(o == b); // true. use toString on p to turn it into a string. console.log(p == "2"); but I think it’s all pretty understandable although Iguess the most“impressive” for me is that one of; var b = true; var o = {x : 1}; o.toString = function() { return("01"); } console.log(b == o); where if I interpretbehvaviour correctly, the boolean is converted to a number and then the object is converted to a number and then they are equal Reference: Flanagan, “JavaScript The Definitive Guide”, Page 71.
  • 17. WTF #11 – Magic of Short-Circuiting ANDs and Truthy/Falsy I really like this one. I find in a language like C# it can be quite painful to index into a complex objectmodel while all the time trying to protect yourselffrom the pains ofa null reference exception. The magic of the AND operator returning the rightvalue at the right time looks to make this a lot easier in JavaScript which I really rather like; "use strict"; var policy = { holder: { firstName: "Fred", lastName: "Smith", age: 45 } }; // like this :-) var age = policy && policy.holder && policy.holder.age; console.log(age); Reference: Flanagan, “JavaScript The Definitive Guide”, Page 123.
  • 18. WTF#12 – Function Arguments I think it was C# 4.0 that finally got around to the notion of optional and named arguments to a function whereas JavaScript is way ahead with the sortof zany stuff that you get to do when writing a function. "use strict"; function f (a, b, c) { console.log("Arg a present " + (a !== undefined)); console.log("Arg b present " + (b !== undefined)); console.log("Arg c present " + (c !== undefined)); if (arguments.length > 3) { for (var i = 3; i < arguments.length; i++) { console.log("Extra argument " + arguments[i]); } } } // too few args leaves b,c undefined. f(10); // too many args is not a problem. f(10,20,30,40,50); Reference: Flanagan, “JavaScript The Definitive Guide”, Page 171-173.
  • 19. WTF #13 – Nested Functions I really like the very natural way that I can define functions inside offunctions in JavaScriptand, optionally, form closures over the local variable state. "use strict"; function moduloCounter(modulo) { // only way to get back to this variable will be via functions // I return keeping it out of anything publicly accessible. var counter = 0; return ( { inc: function () { counter++; if (!(counter - modulo)) { counter = 0; } return (counter); }, dec: function () { counter--; if (counter < 0) { counter = (modulo - 1); } return (counter); }, valueOf: function () { return (counter); } } ); } var module8 = moduloCounter(8); for (var i = 0; i < 16; i++) { console.log(module8.inc()); } for (var i = 0; i < 16; i++) { console.log(module8.dec()); } That’s pretty clever stuff although it takes a bit of getting used to and it feels that this sortof technique has a lot of power to it. Reference: Flanagan, “JavaScript The Definitive Guide”, Page 166.
  • 20. WTF #14 – Arrays versus Lists Arrays seem fairlyeasy to get to grips with in JavaScript but there’s a few differences to whatyou’d see in .NET that leads to the JavaScript array feeling more like .NET’s ArrayList in many ways. One is around the idea that I can just add things to an array whenever and wherever I feel like it; var myArray = [1, 2, 3]; myArray.push(4); console.log(myArray); // 1,2,3,4 var last = myArray.pop(); console.log(myArray); // 1,2,3 myArray.unshift(0); console.log(myArray); // 0,1,2,3 var first = myArray.shift(); console.log(myArray); // 1,2,3 myArray[99] = 'mixed content'; console.log(myArray.length); // 100 console.log(myArray[98]); // undefined console.log(98 in myArray); // false myArray[98] = undefined; console.log(myArray[98]); // undefined console.log(98 in myArray); // true // arrays are still objects of course myArray.whatever = "anything I like"; console.log(myArray.whatever); and there’s the difference between an array “element” being in the array and undefined versus it simplynot being in the array which I tried to highlight.There’s also a lack of multi-dimensional arrays butthat’s not so hard to solve with arrays of arrays. Reference: Flanagan, “JavaScript The Definitive Guide”, Page 151,152.
  • 21. WTF #15 – Function Invocation Context & Strict Mode I find this one a bit tricky (to say the least).If I’m writing a plain old,vanilla function then the this pointer is setto the global object? Ouch! function foo(){ this.x = 10; } foo(); console.log(this.x); // 10, scary :-) It’s “nice” to see that ES5 strict mode comes along and try to tidy this up but I don’tsuppose thatoffers much consolation outside ofa strict environment. "use strict"; function foo(){ this.x = 10; // TypeError: cool! } foo(); console.log(this.x); I could see hours going down the drain to bugs introduced by those kinds ofproblems. Reference: Flanagan, “JavaScript The Definitive Guide”, Page 167.
  • 22. WTF #16 – Nested Functions & Invocation Context This feels like another “gotchya” to me and combines with WTF #15 above. If I have a nested function inside a method; this.x = 101; var myObject = { x: 1, y: 1, myFunction: function() { var myNestedFunction = function() { return(this.x); }; return(myNestedFunction()); } }; console.log(myObject.myFunction()); then even it picks up the global objectfor its invocation context unless I’m in strictmode when it throws an error. What I should be doing is picking up the this pointer myself such that the nested function captures itbut that’d be easy to forget "use strict"; this.x = 101; var myObject = { x: 1, y: 1, myFunction: function() { var self = this; var myNestedFunction = function() { return(self.x); }; return(myNestedFunction()); } }; console.log(myObject.myFunction()); Reference: Flanagan, “JavaScript The Definitive Guide”, Page 169.
  • 23. WTF #17 – Everything’s a Function There’s a piece of code in Crockford’s book that I had to read about 5 times.He (very tersely) defines a new method on all functions called method (this is his code below); Function.protoype.method = function(name, func) { this.prototype[name] = func; return(this); }; because it’s altering the prototype for Function I read that as adding a method (called method) to every Function objectand that new method knows how to add another method of a given name and implementation to the prototype. Wow. It’s used something like below and Ithink it’s fairly well known/understood/etc; String.method( 'lengthSquared', function() { return(this.length * this.length); } ); My function here makes a new lengthSquared function available on any string. The brilliance ofthis is quite something butfor the firstfew readings ofit, I kept saying to myself; “How can Function.protoype be used to add a method to a String when String is not a function. It’s a class or a type butnot a function!!” because Iwasn’tthinking like JavaScript – of course String isn’ta class or a type, it’s a function. In fact – I think I’ll call this “Mike’s FirstLaw of JavaScript – It’s a Function, Stupid” Reference: Crockford, “JavaScript, The Good Parts”, Page 33.
  • 24. WTF #18 – parseInt() needs help I hadn’tappreciated thatthis would happen and that, by default, the “09” would be interpreted as octal; var myString = "09"; var myOctalInteger = this.parseInt(myString); var myDecimalInteger = this.parseInt(myString,10); console.log(myOctalInteger); console.log(myDecimalInteger); Reference: Stefanov, “JavaScript Patterns”, Page 23.
  • 25. WTF #19 – There is no Integer Numerical calculations are comparatively slow because there is no Integer type, only Number - and Number is an IEEE floating point double-precision (64 bit) type. This means that Number exhibits the floating point rounding error: 0.1 + 0.2 === 0.3 //false Since there's no distinction between integers and floats, unlike C# or Java, this is true: 0.0 === 0; //true Finally a Number puzzle. How can you achieve the following? a === b; //true 1/a === 1/b; //false The answer is that the specification of Number allows for both positive and negative zero values. Positive zero equals negative zero, but positive infinity does not equal negative infinity: var a = 0 * 1; // This simple sum gives 0 var b = 0 * -1; // This simple sum gives -0 (you could also just // do "b = -0" but why would you do that?) a === b; //true: 0 equals -0 1/a === 1/b; //false: Infinity does not equal -Infinity
  • 26. WTF #20 – Floating point arithmetic This can be a major cause of frustration for people who are new to JavaScript and are trying to perform some kind of mathematical computation. 1. <script> 2. alert(0.02 / 0.1); //0.19999999999999998 3. alert(1.14 * 100); //113.99999999999999 ;) 4. </script> This is where the Math.round() functions come in handy > Math.min() < Math.max() false This makes sense – they’re functions which normally expect arguments. Without arguments, default behaviour is to return Infinity for Math.min() and -Infinity for Math.max(). And so Infinity < -Infinity === false
  • 27. WTF #21 – Plus operator overloading The plus operator stands for both arithmetic operations and also string concatenation. This is convenient if used correctly. Let's take a look 1. var msg, one="1"; 2. msg = 2 + "1"; // msg = "21" 3. msg = 2 + one; // msg = "21" 4. msg = 1 + 1 + 1 + " musketeers"; // msg = "3 musketeers" 5. msg = "Bond " + 0 + 0 + 7; //msg = "Bond 007" 6. </script> The above behaviour is because the operations are performed left to right. If we use parentheses the behaviour will change based on the order of the string or number in it. Can you work out as to what the below will alert? function foo() { var a = "5"; var b = "4"; alert(+a + +b); } JavaScript is looselytyped, except in switch statements.JavaScriptis NOT looselytyped when it comes to case comparisons. var myVar = 5; if (myVar == '5') { // returns true since JavaScript is loosely typed alert("hi"); //this alert will show since JS doesn't usually care about data type. }
  • 28. switch (myVar) { case '5': alert("hi"); // this alert will not show since the data types don't match } WTF #22 – Undefined Can Be Defined OK, let’s end with a silly, rather inconsequential one. Strange as it might sound, undefined is not actually a reserved word in JavaScript, even though it has a special meaning and is the only way to determine whether a variable is undefined. So: var someVar; alert(someVar == undefined); //evaluates true So far, so normal. But: undefined = "I'm not undefined!"; var someVar; alert(someVar == undefined); //evaluates false!
  • 29. WTF #23 – Misc instances and default values When you create instances of String or Number, they take the default value ("" for strings and 0 for numbers). This is not the same for Object and Array. var a = new Number; a == 0 // true var a = new String; a == "" // true var a = new Object; a == {} // false var a = new Array; a == [] // false This is even more confusing when using the JSON-style syntax to create objects and arrays. var a = {}; a == {} // false var a = [];
  • 30. a == [] // false boolean paradox "0" && {} // true 0 && {} // false, ok...fair enough 0 == "0" // true, wtf! [] == ![] // true, wtf! coerced Careful w/ number type coercion! a = 012 // 10 concat coerce "3" + 1 // '31' "3" - 1 // 2 "222" - -"111" // "333" (⊙﹏⊙) true has a value (true + 1) === 2; // true (true + true) === 2; // true true === 2; // false
  • 31. true === 1; // false coerce equality 3 == "3" // true null is not falsy [] == false; // true "" == false; // true null == false; // false, that's more like it null is not an object typeof null // object null instanceof Object // false Classic null is not an Object. more coerce fun 3 == "03" // true! not a number is a number typeof NaN // number, of course.
  • 32. Now that makes sense. References: http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/default.aspx http://wtfjs.com/ http://bonsaiden.github.com/JavaScript-Garden/ http://blog.boyet.com/blog/javascriptlessons/ http://appendto.com/blog/2011/05/good-javascript-habits-c-developers-elijah-manor http://channel9.msdn.com/Events/MIX/MIX11/OPN08 http://jqfundamentals.com/book/index.html http://osteele.com/sources/javascript/functional/ http://addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatternsjavascript http://robertnyman.com/category/javascript/ http://javascriptweblog.wordpress.com/ http://shichuan.github.com/javascript-patterns/
  • 33. https://github.com/itpastorn/programmering-1-med-js/blob/master/javascript-quirks.markdown Books: JavaScript:The DefinitiveGuide by David Flanagan Object-Oriented by Stoyan Stefanov JavaScript:The Good Parts by Douglas Crockford JavaScriptPatterns by Stoyan Stefanov High Performance JavaScriptby Nicholas C.Zakas High Performance Web Sites by Steve Souders Eloquent JavaScriptby Marijn Haverbeke Secrets of the JavaScriptNinja by John Resig Advanced JavaScriptby Chuck Easttom Head FirstJavaScriptby Michael Morrison