Scope in JavaScript (Learning is fun)

What would you expect when you ran the following code JS snippet ?

if (true) {
var x = 69;
}
alert(x);

Today I found out some interesting things about scope in JavaScript. At the moment I’m reading the book Secrets of the JavaScript Ninja and in the chapter I’m reading they are going back through the fundamentals of functions.

Here is one of the points made is around variables, functions and their scope:

  • Variable declarations are in scope from their point of declaration to the end of the function within which they’re declared, regardless of block nesting.
  • Named functions are in scope within the entire function within which they’re declared, regardless of block nesting. (Some call this mechanism hoisting.)
  • For the purposes of declaration scopes, the global context acts like one big function encompassing the code on the page.

The code at the top will actually alert 69 when run. This came as a bit of a shock for me because from my background of C# / Java I have always assumed x would have been out of scope due to the block level context of how those languages work. When executed i expected to see a healthy null alerted.

This whole time I have made the assumption that these same rules from my experience with C# applied with JavaScript. This realisation that part of the fundamentals of what I have learnt is a little flawed is a little humbling but it really opens your eyes to what you are re-learning and quite honestly it’s awesome.

I can’t believe I have been using JavaScript for so long and have never picked this up. I guess the situation never came up in anything I’ve written (or it has and no one has found it yet). Sure the situation would rarely come up and it’s not like what you are doing is wrong, you just don’t feel like an expert anymore and that’s the humbling part so it’s bitter-sweet.

I KNOW KUNG FU

The great thing is at the moment i feel like Neo (Matrix Movie) when he’s in the chair and Link just ran the procedure to push Kung Fu 1.0 into his head, this will definitely change the way i write JavaScript.

I guess its another notch on the sword on the way to ninja status….

Or maybe I’m just holding the sword the right way round now :)

RELAX, leave backbone alone

I have been playing with backbonejs and CouchDB in my (limited) spare time to see how usable they are together.

Well I have a backbone collection and figured I would fetch a couch view into the collection. Now backbone expects an JSON array and couch gives you a single JSON object that has total and a rows etc.

Image

Hmm…

I started to look around for someone on git that may have done this, not much luck. There were a couple of customisations that have been written but there were a few issues with using the latest backbone release.

I figured I’d start writing my own backbone extension that overrides the sync and fetch functions. I had already done a simple OData JSONP extension for work so I got started.

Then something in the back of my mind said ….list….

I realised you didn’t need to modify backbone, I could use a list function in couch. I even found someone on stackoverflow that had already written one (WIN)

ImageThe more I think about it couch is designed to do things like this, it will add in etags to help cache the list and I can even modify the list to handle different content types.

Hope this helps in some way.

Beautify JavaScript + JSONP = HappyFamily

If you are using JSONP to do cross domain grabbing of data to show on a page often you will want to see the raw response in your browser. The issue with this is it can get confusing because the browser just dumps the JSONP response to the window.

Enter jsbeautifer

All this website does is format your JavaScript to be more readable. I commonly use this site with JSONP responses and for all the times i have used this page I am glad it’s free.

Have a try, grab some JavaScript, JSON, etc.. and paste it into the window and click beautify. 

Enjoy

Closures

Today i read about closures in JavaScript. It was curiosity that forced me to look at this and after reading a few posts and examples on stack overflow I think i have it down pat now.

 

I particularly like the post with references to unicorns :)

closure
This whole curiosity into closures was just to clarify my understanding of what closures were in JavaScript and has actually made me realize why certain things are done in toolkit’s.

Level Up

JavaScript is evolving

I’ve been playing with JavaScript since I first discovered it in grade 9 of high school. At the time I thought it was awesome, I could change images on a HTML page and make stuff disappear. I was hooked.

I started making little web pages that did nothing. I probably contributed to the large amount of webpages on the Internet that had scrolling marques or flaming gifs and had images that switched to different sized images when you rolled over them. For this I am sorry.

js logo

At university JavaScript was not a commonly talked about language, we learned C / C++ and then moved on to Java. These where heavy lifting languages, they could do anything. I couldn’t do it as easy as I could with JavaScript and HTML, but there was more here.

At the time Java and .NET were on the rise and web applications were still a little young. As I matured I saw JavaScript as more of a scripting language and only used when it was need.

Over time I have became familiar with .NET and saw it as a professional language (don’t hate) and JavaScript remained in the background and only took stage when needed.

Now I have noticed something. More and more technologies are pushing the boundaries of where Javascript can be used. Things like node.js have turned Javascript on it’s head and made me think differently about the language, it can be a server now.

Things like require.js, backbone.js, mustache.js, etc.. all push JavaScript to the realm of being a modularised, testable language that follows an MVC architecture. JQuery UI and ExtJS give you rich UI/UX tools that make your apps pop. No more flaming gifs for me.

At the moment I’m hacking together an app that utilises JQuery, mustache and backbone and require. Built with node and CouchApp and pushed to CouchDB, furthermore I am developing it on Cloud 9 IDE. All bar CouchDB are based on JavaScript (As far as I know from what I have read), that’s end to end development in the cloud. To me JavaScript is becoming the language of the Internet.

mustache jsIts like JavaScript is that girl in high school that you hung out with and did stuff with but never got serious with her, she had potential but you were young and naive and never saw it. You grew apart over the years and then suddenly at a conference in Capital City you see her again and POW you are stunned at her change. She is so much cooler than you ever knew…. I think I’m getting carried away.

The point is JavaScript with all it’s fancy prototyping is evolving and I feel like there is a new wave of frameworks that are going to become the norm. Its not going to replace things like Java, PHP, .NET, etc. but I think the convenience and ease that these toolkits create will be big attraction for developers.

Granted it isn’t there yet, things like Unit Testing need a bit of work but in any case I think its an exciting time.

Single Page Apps

I mentioned in a previous post about single page apps and how Mikito Takada put the idea of views being objects and not templates in my head. Well I thought I would share the link that very briefly mentions this and a few other concepts. The video is called Adventures in Single Page Apps.

Takada explains how the traditional world of MVC based applications doesn’t entirely fit the bill for the single page app world when it comes to code reuse and testing. He introduces a few concepts here that are very interesting and make sense to me but I need to read a bit more into this to see if it’s practical.

I might also add this video is in the realm of ajax based web applications with heavy use of Javascript and Javascript based frameworks like node.js and backbone.js.

Its an interesting video and some of what is talked about make sense, just some more investigation on practicality needs to done in my view.

Anyhoo enjoy.