Lars Nielsen's Discoveries

January 19, 2013

JavaScript Patterns book

Filed under: Architecture,Development,SharePoint — Lars Nielsen @ 2:00 pm

With SharePoint 2013 and HTML 5 it looks like the future is Javascript.  I’m personally not convinced that the demise of Flash will lead to improved security – many exploits are actually injected through Javascript and things like federated authentication provide new scope for exploits (just Google “Facebook fake logon” to find out all about it!).   But anyway clearly Javascript is becoming more and more important and I found this great book, JavaScript Patterns, which demonstrates more than a few features of the Javascript language.  Reading this book you really begin to see how, despite being syntactically similar to C# or Java, Javascript is truly different.

Here’s an interesting example :

var city = "Washington";

function alertCity()
   var city;
   city = "New York";

If you try this code in a page you find that the first alert call outputs not (as you might expect) “Washington” but “Undefined”.   The second one outputs “New York”.  This is because the var city statement inside the alertCity function is hoisted up to the beginning of the function, as if it were declared at the beginning of the function.  It hides the global variable city and it becomes an uninitialised variable.  Later it’s initialised, and so the second alert behaves as you might expect.  It’s a good example of why you should always declare variables with a var statement at the beginning of a function.

Reading through this book I’ve come to realise that JavaScript’s treatment of functions as objects is in many ways closer to functional programming than many other of the “C-like” languages like Java or C#.  Most of the time I must admit I tend to write Javascript as if it was C# without types, and I guess many .NET or Java developers do the same. But it’s worth knowing that when working in Javascript, you can do clever things like curry functions which, in the C# world for example, have only relatively recently become possible with the introduction of lambda expressions.


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at

%d bloggers like this: