null + null = 0, +new Date, and why loosely typed languages like Javascript are a pain

Javascript is a loosely typed language. This was done to expedite the writing of code and avoiding tedious tasks such as declaring variables and explicitly defining their types. You know, the kind of stuff only suckers would do. The irony is that these so called shortcuts actually result in more tedium as everything requires a tremendous amount of type checking. Consider the simple act of concatenating two strings: str1 and str2.

str1.concat(str2) fails immediately if str1 is undefined or null, so the concat method is out of the question. But we can always use the javascript “+” operator right? Sure, if you want to trust the implicit type casting in Javascript. In a strongly typed language such as C#, if str1 and str2 are null, str1 + str2 results in null as well. The result is intuitive and expected. In Javascript, the result of str1 + str2 is the integer value 0. This can lead to some hilarious and unintended consequences in the code that can be a pain in the ass to track down. But wait, there’s more! If both str1 and str2 are undefined, str1 + str2 is NaN (not a number). If str1 is “” and str2 is null, then str1 + str2 is equal to “null”. That’s right, because str1 is a string, Javascript implicitly casts str2 as a string as well. The expression becomes “” + “null” which evaluates to “null”. Ugh. If str1 is “” and str2 is undefined, well guess what? The string, “undefined”, is what happens when you concatenate the two.

If you want a result that is not nonsensical, you wind up having to write to some hideous code to convert all null and undefined values to an empty string first:

if (str1 === undefined || str1 === null)
{
    str1 = "";
}

if (str2 === undefined || str2 === null)
{
    str2 = "";
}

var result = str1 + str2;

And yes, the triple equals is absolutely necessary. Without it, the implicit casting rears its ugly head again. So to sum up, use common sense when writing Javascript code. Stick with the basic best practices.

DECLARE YOUR VARIABLES.

str1 = "hello"; //BAD but valid, sets str as a property of a global object. That's right, str1 is now a global variable. Horrible
var str2 = "world"; //You have to type three extra characters but it saves you a ton of grief

DO NOT USE YOUR VARIABLES FOR MORE THAN ONE PURPOSE

var str1 = "hello";
console.log(str1);
str1 = 5;  //For the love of god, just declare a new variable here instead
console.log(str1);

DO NOT DO CUTE STUFF WITH IMPLICIT CASTING TO LOOK COOL

var start = +new Date();

This is a clever snippet of code, but it can be rewritten to this functionally equivalent:

//short hand for
var startDateTime = new Date();
var startTicks = startDateTime.getTime();

Both versions of the code do the same thing. The second requires a bit more typing but is far more readable. +new Date is gimmicky. Yes it “looks cool” and shows off your Javascript skillz, but the brevity in this case is detrimental in the long run to maintainability. +new Date works because it first creates a new Date object. By default, the Date constructor returns the current date. The “+” unary operator is applied, which implicitly casts Date to an integer. The implicit casting returns the number of ticks since 1/1/1970. Great, but why have this esoteric code? It relies on an implicit cast, so it is entirely on the version of Javascript and the browser it is running on. Any future changes could potentially break the code . If typing two lines instead of one is so painful, create a utility function instead that calls +new Date and slap a comment on there. Or don’t, because +new Date has horrible performance.

So remember, scripting languages such as javascript make writing code easy, but the ease of use leads to ease of abuse. Be careful or you’ll wind up making things more difficult in the long run.

Scoping of “this” – client side Javascript versus server side NodeJS

Every function in Javascript has a “this” object that behaves differently depending on the execution context. Everytime a function is executed in Javascript, there is an object context associated with it; “this” provides a way to reference that object. When calling an object method, such as Foo.bar(), “this” refers to the Foo object. When calling a method in a global context, such as bar(), “this” refers to the Javascript global object. In most browsers, that would be the window object. bar() is essentially shorthand for window.bar().

Now, the behavior in NodeJS is quite different. In order to prevent pollution of the global namespace, all functions running in the top level scope are not scoped to the global object, but to a unique local object instead. That means every function in Node has its own “this” variable. According to the official NodeJS documentation:
In browsers, the top-level scope is the global scope. That means that in browsers if you’re in the global scope var something will define a global variable. In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.

Consider the following code:


function somefunc() {
    this.value = 100;
    console.log("this.value inside somefunc() is " + this.value);
}

this.value = 1;
somefunc();
console.log("this.value in top level scope is " + this.value);

The nodeJS output is:

this.value inside somefunc() is 100
this.value in top level scope is 1

The output from the javascript console in a browser such as Chrome or Firefox is:

this.value inside somefunc() is 100 
this.value in top level scope is 100 

Because somefunc is attached to the global object, “this.value” actually refers to window.value. Thus, changing the value of “this.value” inside somefunc() changes window.value, so “this.value” is still 100 even after somefunc() has finished execution. In NodeJS however, “this.value” inside somefunc is not the same “this.value” outside of somefunc. Again, every function has its own “this” variable, scoped to the object that it is referenced in. In NodeJS, the same holds true for anonymous functions as well:

 
function somefunc(cb) {
     this.value = 100;
     console.log("this.value inside somefunc() is: " + this.value);
     cb();
}

this.value = 1;
somefunc(function() {
    this.value = 50;
    console.log("this.value inside the anonymous function is: " + this.value);
});

console.log("this.value in top level scope is " + this.value); 

NodeJS outputs:

this.value inside somefunc() is: 100
this.value inside the anonymous function is: 50
this.value in top level scope is 1 

The browser outputs:

this.value inside somefunc() is: 100 
this.value inside the anonymous function is: 50  
this.value in top level scope is 50 

As before, the browser behavior is a result of somefunc being executed in a global context. In the preceding code, this.value always refers to window.value, even when it appears inside the anonymous function callback (more on this later). In NodeJS, the anonymous function has its own “this” object that is different from the “this” object inside somefunc. This results in the three different values for “this.value”.

Now let’s take a look at what happens when we explicitly set the execution context of somefunc to that of a local object:

function somefunc(cb) {
     this.value = 100;
	 console.log("this.value within somefunc is: " + this.value);
     cb();
}

var obj = {
    method:somefunc
};

this.value = 1;

obj.method(function() {
    this.value = 50;
	console.log("this.value within anonymous function is: " + this.value);
});

console.log("obj.value is: " + obj.value);
console.log("this.value in top level scope is: " + this.value);               

The browser prints out:

this.value within somefunc is: 100  
this.value within anonymous function is: 50  
obj.value is: 100  
this.value in top level scope is: 50 
this.value within somefunc is: 100
this.value within anonymous function is: 50
obj.value is: 100
this.value in top level scope is: 1 

When run from a browser, obj.value is set to 100 and window.value is set to 50. Since somefunc is no longer being called from a global context, “this” inside somefunc is owned by the object that calls it (imaginatively named obj in this example). “this.value” is actually referencing obj.value. Note that the anonymous callback function, “this” is not scoped to obj, but rather the global object. Because the anonymous function is not explicitly called via an object context, it still defaults to a global context!

The behavior in Node is consistent with what we observed before. When called in an object context, the “this” object inside of somefunc refers to obj. The anonymous function has its own “this” object, and any modifications to it are not reflected in obj nor in the top level scope. As a result, obj.value is 100 whereas this.value remains 1 in the top level scope – it was initialized once and never modified again.

The key takeaway here is that “this” can be incredibly confusing and unintuitive. Javascript provides methods such as apply() and call() methods for a reason: so that you can explicitly set “this” and avoid all the headache second-guessing yourself trying to figure out what “this” actually is.

Exploring Javascript closures

Javascript closures are a concept that is easier to explain by example:

function outer(increment) {
    var outer_foo = 1;
    function inner() {
        outer_foo += increment;
        return outer_foo; 
    }
    return inner;
}

var outer_instance = outer(2);
var foo1 = outer_instance();
var foo2 = outer_instance();  

alert(foo1);   //3
alert(foo2);   //5

The inner function references the local variables of the outer function. The inner function is the closure. It is enclosed by its parent function and has access to its parent’s execution context, even after the parent has finished execution and returned. In essence, variables in the scope chain of the parent function stay in scope, as though they were allocated on the heap and not on the stack. Contrast this to programming languages such as C, where parameters and variables local to a function are declared on the stack frame, and immediately deallocated after the function has exited.

Because the parent function’s variables stay in scope and are essentially passed by reference to the closure, this can lead to bugs. Case in point:

function createFunctions() {
    var result = new Array();

    for (var i = 0; i < 10; i++) {
        result[i] = function() { return i; };
    }

    return result;
}

var functionArray = createFunctions();
var func1 = functionArray[0];
var foo1 = func1();  
alert(foo1); //10
var func7 = functionArray[6];
var foo7 = func7(); 
alert(foo7) //10

The createFunctions method returns an array of closures, each of which is a function that returns the value of the loop index, i. At first glance, it would seem as though the closures would return the numbers 0 through 9, respectively. In actuality, every closure in the array returns 10. This is because the i variable in each closure references the i variable of the parent execution context. Because this is a reference, the value of i will not be the value at the time of the creation of the closure, but rather at the time of the execution of the closure. The for loop will have already terminated by this point and set i to 10.

In order to match the original intent behind the function, createFunctions() can be rewritten as follows:

function createFunctions2() {
    var result = new Array();

    for (var i = 0; i < 10; i++) {
        result[i] = function(num) { 
	    return function() {
	        return num; 
	    };
	}(i);
    }

    return result;
}

This syntax can be a bit jarring to read at first. The inner-most anonymous function is a closure that references the variable num, which is scoped to its parent function:

 
    //snipped out code ... 
        function() {
            return num; 
        }
    //...

The inner function is the return value for its parent function, which takes in a single argument: num. This parent function is immediately invoked with the loop-counter i as its parameter, as denoted by the “(i)” found at the end of the function declaration.

//snipped out code ...
        function(num) { 
	   //...
	}(i);
//...

Because parameters are passed in by value and not by reference, num retains the value of i at the time this outer function was created. In other words, num will equal the value of i at the current iteration in the for loop, and will keep this value independent of any future modifications to i. The outer anonymous function serves as an intermediary: It returns a closure that returns the value of num “frozen” at that point in time, allowing the code to function as originally intended.

   function createFunctions2() {
	var result = new Array();

	for (var i = 0; i < 10; i++) {
		result[i] = function(num) { 
			return function() {
				return num; 
			};
		}(i);
	}

    return result;
}

var functionArray = createFunctions2();
       
//prints out the numbers 0 through 9
for (var i = 0; i < 10; i++)
{
	var bub = functionArray[i]();
	alert(bub);
}

The key takeaway here is that closures access variables in their parent’s scope chain by reference, and not by value. To bypass this intended behavior, the parent variables that the closure accesses must themselves by a copy of the originals, which is accomplished by passing them in as parameters to the parent function. The code that accomplishes this can look unwieldy, but its not so bad once you figure out the basic pattern behind it.

json-schema how to reference other schemas in jsonschema2pojo

I’ve been using the jsonschema2pojo utility at work to automatically generate java classes from JSON schemas, simplifying a lot of the tedious code that needs to be written for the marshalling and unmarshalling of JSON objects. JSON schema is a developing standard that is analogous to what XSD is to XML, providing schema definition and validation for JSON. Just like with XSD, a JSON schema can reference other schemas. This is done by using the special object property $ref.

The following is a simple JSON schema for an address object. Assume that it is stored in the file, Address.json:

{
    "id":"Address",
    "title": "Address",
    "description":"This is the json schema for an address",
    "type": "object",
    "properties": {
        "streetAddress": {
            "type": "string"
        },
        "city": {
            "type": "string"
        },
        "state/province": {
            "type": "string"
        },
        "zipcode": {
            "type": "string"
        }
    }
}

Here is a simple JSON schema for a person object. A person object contains an address. To reference the previously defined address schema, add an address object that contains a $ref property pointing to the filepath of the Address.json file:

 
{
    "id": "Person",
    "title": "Person",
    "description":"This is the json schema for a person",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string"
        },
        "lastName": {
            "type": "string"
        },
        "age": {
            "description": "Age in years",
            "type": "integer",
            "minimum": 0
        },
        "address": {
            "$ref": "Address.json"
        }
    }
}

Note that both relative and absolute pathing work in jsonschema2pojo.

To add a reference to a list of addresses, add an “addresses” object with a “type” property of array and an “items” object. Add a $ref property under “items” that points to the filepath of Address.json:

{
    "id": "Person",
    "title": "Person",
    "description":"This is the json schema for a person",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string"
        },
        "lastName": {
            "type": "string"
        },
        "age": {
            "description": "Age in years",
            "type": "integer",
            "minimum": 0
        },
        "addresses": {
            "id" : "addresses",
            "type": "array", 
            "items": { "$ref": "Address.json" },
            "uniqueItems": true
        }
    }
}

jsonschema2pojo will generate a Java class that contains a List of Address objects. Incidentally, adding the property “uniqueItems”:true it becomes a HashSet of Address objects.

A free schema generation tool is available at http://www.jsonschema.net/. When paired with utilities like jsonschema2pojo, it makes life for developers that much easier.

Does Javascript pass by value or pass by reference?

Javascript exhibits quite interesting behavior when it passes object parameters. At first glance, it would appear that it passes everything by reference. Consider the following HTML page.

<html>
<body>
<script type="text/javascript">

    function MyObject() {
        this.value = 5;
    }

    var o = new MyObject(); 
    alert(o.value); // o.value = 5

    function ChangeObject(oReference) {
        oReference.value = 6;
    }

    ChangeObject(o);
    alert(o.value); // o.value is now equal to 6

</script>

</body>
</html>

We initialize an object o by calling the MyObject() constructor. The constructor sets the value member to 5. We then pass o into the ChangeObject() function, where it sets the value member to 6. If o were passed by value, that would mean we are passing a copy of o, and that its value member would not be changed once the function exits. However, if we open up this HTML page in a browser, the final alert(o.value) indeed prints 6. This would lead us to conclude that Javascript passes by reference.

However, things get really interesting when we look at this HTML page.

<html>
<body>

<script type="text/javascript">

    function MyObject() {
        this.value = 5;
    }

    var o = new MyObject();    
    alert(o.value); // o.value = 5

    function ChangeObjectWithNew(oReference) {
        oReference = new MyObject();
        oReference.value = 6;
    }

    ChangeObjectWithNew(o);
    alert(o.value); // o.value is still 5

</script>

</body>
</html> 

This page is identical to the last, with the slight modification that we call the ChangeObjectWithNew () function. ChangeObjectWithNew creates a new instance of MyObject and assigns it to oReference, and then sets this new instance’s value member to 6. If Javascript passed by reference, o would now point to this new instance, and its value member would be 6 after ChangeObjectWithNew ran. However, if you run this page in a browser, the final alert(o.value) still prints 5. How is this possible?

What is happening behind the scenes is that Javascript is passing a reference of o by value. This can be a little confusing, so think of it this way. When o is first declared and initialized, it points to the memory location of the actual object that we instantiated. When the ChangeObject function is called, it passes in a copy of this pointer that points to the exact same memory location. Thus any changes to oReference’s member variables will be reflected in o, since both point to the same spot in memory. However, when we call ChangeObjectWithNew, the line “oReference = new MyObject” now causes to point to an entirely different spot in memory. Thus any further changes to oReference’s member variables will no longer be reflected in o.

A picture helps clarify things.

Here is what the situation looks like when we call ObjectChangeWithNew:

After ChangeObjectWithNew has run, note that oReference now points to a new memory location.

Since Javascript hides the implementation details behind how it handles its pointers, this C program demonstrates passing by reference and passing a “reference” by value. ChangeObject is called with a pointer to MyObject. This is passing by reference. ChangeObjectWithNew is being called with a copy of the original MyObject pointer. As a result, modifying its value member does not modify the original pointer’s value member.

#include <stdio.h>
#include <stdlib.h>

typedef struct 
{
    int value;
} MyObject;

void ChangeObject(MyObject * objReference)
{
    (*objReference).value = 6;
}
 
MyObject * ChangeObjectWithNew(MyObject * objReference)
{
    objReference = (MyObject *)malloc(sizeof(MyObject));
    objReference->value = 6;
}

int main(int argc, char* argv[])
{       
    MyObject * o = (MyObject *)malloc(sizeof(MyObject));  
    MyObject * oCopy;  //this will be a copy of the original object pointer      
    oCopy = o;

    printf("Setting o->value to 5");
    o->value = 5;
    printf("MyObject.value: %d\n", o->value);
    
    //now pass by reference
    printf("Calling ChangeObject with original pointer\n");
    ChangeObject(o);  //this will change o->value to 6    
    printf("MyObject.value: %d\n", o->value);  //prints 6

    //reset o->value to 5
    printf("Resetting o->value to 5\n");
    o->value = 5;
    printf("MyObject.value: %d\n", o->value);  //prints 5

    //now pass a COPY of the origal pointer
    //this is how Javascript behaves, minus the memory leak
  
    printf("Passing in a copy of the pointer o to ChangeObjectWithNew\n"); 
    oCopy = ChangeObjectWithNew(oCopy);
    printf("MyObject.value: %d\n", o->value); //still prints 5

    //free the memory 
    free(o);
    free(oCopy);
    o = NULL;
    oCopy = NULL;

    scanf("Press any key to continue");
}

The fact that Javascript passes a “reference” by value is important to keep in mind. Assuming it passes by reference can lead to some difficult to track down bugs later on.

CIW Javascript Specialist Certification

Last year I got my MCTS EXAM 70-433: Microsoft SQL Server 2008 Database Development certification and wrote about my experience.    To recap, while I doubt that there is much intrinsic value in the certificate itself, the extrinsic value of setting a goal (improving my TSQL skills) and having a test with which I could objectively measure progress was valuable.    It also happened to be one of my annual SMART objectives, which is one of those corporate self development programs.   You know, the kind of stuff that HR comes up with in order to justify their continued existence:   It’s got a clever acronym (what exactly it stands for escapes me at the moment) and tied to your annual performance review too.

This year, for lack of a better imagination, my SMART objective this year was to get a Javascript certification:  In addition to having done a lot of front end development this year, I had also just finished reading all 800+ pages of Professional Javascript for Web Developers.   I searched around online for certifications and was surprised to see that there really weren’t any.     W3C schools has a Javascript certification, but its a self proctored online exam, which means that it’d be of dubious validity at best.   I finally found a CIW Javascript Specialist certification that was administered by Prometric.

I immediately encountered some red flags.    The CIW website has a maximum password length on its account creation page, which I found to be hilarious.     The study guide for the exam assumed that the user had little to no prior programming experience, and seemed to hold your hand every step of the way.    I skimmed a few chapters and decided it wasn’t worth my time.    Much to my disappointment, the actual test proved to be almost comically easy.     I had done all the practice exams the night before, and that had proven to be more than sufficient.    Most of the exam questions were taken almost verbatim from the questions on the practice tests, which weren’t very difficult in the first place.

The questions that tested knowledge of general programming constructs such as if statements and for loops were predictably straightforward.       I rolled my eyes at the multiple choice syntax questions.   These were freebies.  “Spot the valid function declaration” and “which one of these is a valid variable name?” were my favorites.    There weren’t really any questions that dealt with advanced Javascript language features:  I encountered one question about prototypical inheritance.    Probably the most “difficult” part of the exam were the Javascript API questions.   These required a lot of rote memorization.    For example, normally I wouldn’t know the difference between the substr and substring functions and would need to rely on google to find out.      However, after spending a few hours going over the practice problems, they became a non issue on exam day.

The FAQ on the CIW website indicates that the exam was recently updated to reflect major third party APIs such as JQuery.     Well turns out there aren’t actually any questions about JQuery on the exam.   Rather, they threw in some generic questions about how to include JQuery in your web application, as well as some questions about the pros and cons of using third party Javascript libraries.

If the my MCTS EXAM 70-433: Microsoft SQL Server 2008 Database Development  is geared toward those with intermediate to advanced expertise with SQL Server, then the CIW Javascript Specialist certification is geared toward absolute beginners.  Anyone with a rudimentary knowledge of Javascript will be able to pass it.      Even those without Javascript knowledge but who have done nay programming would probably be able to go through the practice exams the night before and pass.   I wouldn’t recommend getting this certification if you have to pay for it out of your own pocket, but if you can convince your company to foot the bill, then go for it.   It’s a “low hanging fruit”, won’t take long, and can’t hurt.

Professional Javascript for Web Developers

Professional Javascript for Web Developers is a comprehensive 800+ page tome that does a deep dive on all things Javascript.     It starts off with a brief history of the ECMAScript standard that Javascript is derived from, before launching into the basics, teaching everything there is to know about types, statements, operators and functions.    These earlier chapters provide a solid basis of understanding that the later parts of the book then build off of.   These sections go into the more advanced language features such as function expressions, closures, prototypes, and inheritance.    In addition, the book also devotes entire chapters to the typical day to day tasks that web developers do on a regular basis: DOM manipulation, forms, AJAX, JSON, and event handling.   Along the way, it manages to cover just about everything else as well, including client detection, XPath, XSLT, and the WebStorage API.   Heck, it even covers 3D graphics programming with WebGL!

When I say the book does a deep dive, I do mean deep.   I had originally intended to skim through the language basics sections, but ended up learning a lot about the various nuances and caveats of Javascript.     For example, due to the dynamically typed nature of the language, there are a lot of “gotchas” involved when using the equality and comparison operators.    This book covers all of them.  While reading the section on variables, I was surprised to learn that all function arguments are passed by value, whereas creating a copy of a reference type (eg var obj1 = new Object(); var obj2 = obj1) merely creates a pointer to the original object on the heap.     Useful information such as this is found throughout the book, and upon completing it, I found myself with a greater appreciation and understanding of the language.

I also gained a greater appreciation of just what a pain in the ass it is to support multiple browsers.    The slight differences in Javascript implementations across browsers (or not so slight, in the case of IE) can be quite problematic for front end developers, so the book takes great pains to discuss techniques to writing cross-browser compatible code.   To that end it spends an entire chapter talking about client detection; the sample code from this chapter is used extensively throughout the later portions of the book.

All in all, I would strongly recommend this book to anybody who is a front end web developer.   The breadth of topics covered makes it a great reference, whereas the depth makes this an excellent textbook as well.   Particularly valuable are the best practices found throughout every chapter.   That in and of itself is reason enough to own this book.   As an added bonus, it is quite funny learning about all the errors in earlier versions of IE’s Javascript engines that were either egregious bugs or blatant disregard for the official standards.

Javascript arguments.callee

All functions in Javascript are instances of the Function type, meaning that they are actually objects. And just like any other object in Javascript, they can have their own set of properties and methods. One such property is the arguments object, which contains a list of all the parameters passed in to the function. The arguments object itself contains a callee property, which points to the function that owns the arguments object. This provides us with a way to reference the function being called while inside of the function body itself.

Why would you want to do this? Well, this can come quite in handy if we want to define a static variable scoped to the function itself. Perhaps the function contains code that performs a particularly complex calculation or an expensive initialization that only needs to be run once. We can store the result inside of a static variable which will improve response time on subsequent calls to this function. For example:

Function createFoo()
{
   If (typeof arguments.callee.bar != “number”) 
   {
       Arguments.callee.bar = ….  //perform expensive logic here		
   }

   //now we can refer to arguments.callee.bar without having to perform
   //the expensive logic again on subsequent calls
}

Using closures to simulate encapsulation in Javascript

Javascript is not an object oriented programming language per se. Although everything in Javascript is an object, there is no real concept of a class construct; objects are simply a collection of key/value pairs. As a result, tenets of OOP such as classical inheritance are not really possible with the language. Instead, Javascript supports “object reuse” through prototypal inheritance. This is a different flavor of inheritance where objects clone key/value pairs from prototype objects. Encapsulation, another key tenet of object oriented programming, is also not directly supported in Javascript either. There are no “public”, “private”, or “protected” keywords.

However, it is possible to simulate private variables through closures in Javascript. A closure is simply a function defined inside another function in Javascript. The closure has access to all the local variables defined within the containing function. Note that any local variable defined within the containing function is not accessible outside said function, as it will no longer be in scope. For example:

function Foo()	
{
	var bar = 5;
}

alert(bar);

This will error, since bar is defined inside Foo, and not accessible from the global context. To get around this, we define a closure inside Foo:

function Foo()
{
	var bar = 5;

        this.IncrementBar = function (){
	    Bar++;
        }
} 

Var myFoo = new Foo();
myFoo.IncrementBar(); 

The IncrementBar() function is defined within Foo() and thus has access to the bar variable. Furthermore, because IncrementBar() is assigned to the “this” object, by instantiating an instance of Foo, the new object will now have a public method with which it can modify bar. The bar variable is local to the Foo() constructor, and hence cannot be accessed from outside. Trying to set myFoo.bar will create a new property on the foo object, but will not override the bar variable declared within Foo(), which is no longer in scope. bar is for all intents and purposes, “private” to the foo object. While using closures is not quite as easy as slapping on a private keyword in front of bar, it achieves the same effect.

Javascript === operator

Like most scripting languages, Javascript is not strongly typed. This causes implicit typing to occur when two variables are compared, resulting in some interesting behaviors. A prime example of this is the equality operator ==. For example, if either operand is NaN, then the equality operator returns false. Even if both operands are NaN, the comparison still evaluates to false, because NaN is not equal to NaN (similar to how comparing anything to an ANSI NULL in SQL evaluates to false).

Or consider the following:

var op1 = “”;
var op2 = true;

if (op1 == op2)
{
    alert(“equal”)
} 

The if statement evaluates to false, because op1 is cast to a boolean. Empty strings are converted to false, and non empty strings are converted to true. However…

Var op1 = “0”;
Var op2 = true;

If (op1 == op2)
{
    alert(“equal”)
}

In this case, the if statement evaluates to false, because “0” is converted to 0, which is not equal to false. If op1 were equal to “1”, then the statement would evaluate true.

To deal with all these caveats and gotchas, Javascript introduced a strictly typed equality operator, ===, and its eqvuivalent inequality operator, !==. These do a strict type comparison, and if the types do not match, the result is false. Thus 0 === “0” evaluates to false. One interesting to note is that null == undefined is true, however null=== undefined is not. This is because null and undefined are not the same type. In order to maintain type integrity in the code, its considered a best practice to use === whenever possible. It also potentially saves on performance, since no implicit casting is performed.