Getting to Know JavaScript Scoping

js-150x150Becoming a Pro in JavaScript requires a few capabilities, one of the most important ones, is understanding JavaScript variable scoping. A lot of developers that came from a different programming language bang their head in the wall often until they fully understand JavaScript scoping mechanism. Let’s start:

What is Scoping?

scope-200x300You can’t access everything from anywhere. Each function and variable in JavaScript has a scope, you may have not been aware to the existence of the scope, but it does exist. A scope is basically an access mechanism to an object, function or variable. if you can access an object than you are in the object scope, and If you have no access, you are out of scope. There is a scope that is accessible from anywhere – the global scope. but let’s first start with the simple scope mechanism – the function scope.

Function Scope

In JavaScript – the scope is changed only in functions and not in any curly braces {..} like in a lot of other languages. so if we look at the next example we can see that we can’t access the ‘bar’ variable since we try to access it outside the function and that means that we try to access a variable out of the scope and that is not possible so the alert will throw a “ReferenceError: bar is not defined”.

The function ‘bar’ has it’s own scope and anything that will be defined in the function could not be accessed outside of the function.

Global Scope

The global scope can be accessed from everywhere, as a rule of thumb there should be as few global scope variable as possible. A lot of global variables can cause conflicts in complex applications.

Access from everywhere means that you can access the global scope from any portion of your code, at any time. When a variable is scoped globally it can also be accessed through the ‘window’ object, I mention that because of the next example:

There are mainly 3 ways to declare a variable in the global scope:

  • Each variable that will be declared in the main script, that means not inside a function will be scoped in the global scope

  • Declaring a variable without using the ‘var’ keyword will cause the variable to be scoped globally, no matter where it was declared. that is a huge pitfall for a lot of beginners.

  • Adding a property directly to the ‘window’ object - = “hello”

From the above example we can learn that although the scoped var foo in the function is now “hello” the original foo variable is still accessible through the window object who holds all the global variables.

As I said before, any variable or function that is declared outside a function or object will be scoped automatically in the global scope.

Always Declare your Variables

When declaring a variable – it should always be prepended with “var”, not doing this will cause the variable to be scoped globally. that can cause an unexpected behavior.

Look at the next example in order to understand how forgetting to prepend a variable with the ‘var’ keyword will cause the ‘bar’ variable to be scoped globally :

To better understand the problem that could arise from this, take a look at the next example:

because ‘i’ is used in foo in the global scope, the ‘var’ was not used… than the alert will not say that “i is true” because ‘i’ is actually equals to zero because we called the foo() function before our if.

so to summarize how you should use any var in a function, don’t use it in a global scope like that:

You might think it is better to do it like this:

but you will be wrong, well, at least not 100% right..
The best way is to declare it at the beginning of the scope:


but… why? well, it is the preferred way because of what is called Hoisting.

JavaScript Hoisting

Hoisting is a strange behavior when you first hearing about it, what it means is that any variables / function that belong to the current scope will be declared at the beginning of the scope. the difference between a variable and a function hoisting is that the function will have a value in the beginning of the scope while a variable will be undefined.

Why is that something that is important to know? take a look at the next example:

you would think that the output will first log ‘hello’ and ‘world’ but it will actually will log ‘undefined’ and ‘world’.
why? Hoisting! that is why… with hoisting your code will actually be interpreted as:

So in order to not be surprised with unexpected behavior – it will be a good idea to always declare any variable that is used in the scope at the beginning of the scope.

Unlike variables, functions have their value when called before their declaration. You can see that from the last example where we called the ‘bar’ function before it was declared, That was possible because of hoisting that was interpreted into:


Scoping in JavaScript can be tricky. but all the common pitfalls can be avoided with the coding conventions I presented – declare all scoped variable at the beginning of the scope and prepend all variable declaration with the ‘var’ keyword.


You should use Underscore.js

I must admit, the first time i encountered Underscore.js i didn’t get it. All I saw is a bunch of functions…

Let me start by saying that you want to use underscore.js, you might don’t know it yet but you want to.

Underscore.js is exactly what it seems – it is bunch of functions. But these collection of functions have one true goal – to make you put your attention on developing your logic and make some operations trivial. If you are familiar with jQuery, than you probably know the benefits of how it is simplifying the DOM manipulation, Underscore.js is similar to that in a manner that it is simplifying data manipulation in JavaScript.

Underscore give your JavaScript coding a turbo engine by giving you functions that let you sort and filter your data really easily.

The easiest way to understand Underscore.js is by an example:

Let’s say that you have a collection (an array of JavaScript objects of the same kind) of student grades and you want to give student id ‘15’ an extra 10 points.

In pure JavaScript it could look like this

In Underscore.js it will look like something like this:

At first it looks a bit weird to use the ‘_’ as an object, but if you got used to the jquery ‘$’ you will get used to this one too.

The findWhere function will go over the collection and will return the first occurrence of the the student with an ‘id’ of ‘15’, this is really efficient because if you have 1,000,000 students – it does not have to go over all of them – as soon as it finds it – it will stop the search.

besides the performance boost and the fact that it was easier to write you can see that it is easier to read – that is an awesome bonus because six month from now when you want to add a cool feature to your code you can understand it better because it is more readable.

Another example is to create a function that returns how many students got a grade that is higher than 85:

And the Underscore.js version:

the function that is passed as a second parameter to the filter function is the actual filter function, that mean that each object that will return true from that function will be added to the filtered collection – in our case each object that has a grade that is higher than 85 will be in the filtered array collection.

We could use some other function called countBy to get a similar (yet different) solution:

As you can see – complex logic can become really easy with the power of Underscore.js functions – and I showed only a few of the more simple ones. You can use complex operations like ‘map’ and ‘reduce’. Reduce function could be used for summing operations over objects, for example:

Let’s say that we have a collection of family, and each object in the family have an income. We want to calculate the total income of the family members. So, that’s easy with reduce:


That’s it! If you wonder what the third argument is then it is the initialization of the sum var – but it can be practically anything.

Underscore has a lot more functions to handle objects and object collections – you can find out all the function reference API on Underscore.js website.

Underscore.js have more features except from from the previous functionality, it has a built in templating function, a simple one, but that is where it is powerful – it is also simple to use…

All Underscore functions are chane-able,  that is another characteristic that was taken from jQuery.

Extending Underscore.js to your own use case:

It is very easy to extend Underscore.js and built on top of it – just use the mixin function to do that:

That example show a simple way to extend Underscore function base to your own, in this case we created a new function called capitalize which capitalize the first letter of the string and turning to lower case any other character.

Please note that in addition to all of the above Underscore also has a section on functions – this section can help you bind function and other helpful development workflow like ensuring a function could get called only once, delayed, run only after called X times and much more.

I want to end this post here, not because I don’t have anything else to add about Undescore functionality – it has a lot more power, that you can discover for yourself in the project website. I encourage you to do so! go ahead and play around

Mini Review of “Secrets of the JavaScript Ninja” By John Resig & Bear Bibeault

jsninj-150x150I have started reading the new book of John Resig, which in case someone don’t know, is the creator of jQuery. I’m just in the beginning (page ~60) – but i still have a few insights that I would like to share:

A free e-book!

When you buy the book, inside of it you get a code which you can use to get the e-book version for free. That was a very nice gesture from Manning that i really like. That way i don’t need to choose, I get both. and it is a great surprise since I was not aware of that.

About the book

I really like how the book is organized, it is well written and addresses the reader in a way that reminded me a private tooter. It does not uses high language and it is very easy to follow, both the text and also the examples.

Who the book is for?

This book is not for a novice developer. If you have a good grasp of JavaScript then this book is for you, it will uncover some of Javascript black magic, with a fun approach. if you are a newbie in Javascript – this book is not for you. you should start with a more basic material and only then read this book. I think every front end developer should read this book – but if you just beginnin – read some more basic stuff and only then return to this book.

Scoping – A small point that was overseen

When the writer is explaining about scoping, he wrote that the function scope is within the entire current scope even if it is defined at the end of the current scope. And in the example that was given it was implied that a variable is not acting like that… But it is! It is available. It is only that the assigned value is available after the assignment, but the variable itself exist in the scope. That maybe sounds like an unimportant point but it could cause an unexpected bugs like in this example:

You would think that the value of ‘test’ will be “I’m out” according to the book explanation, but because of the hoisting nature of Javascript it is actually will be ‘undefined’, hoisting is not only for functions it is also for variables. The only difference is that functions will be defined even if the declaration is after the function call while in variables it is not.

So we can actually say that the above code will actually behave like the next one:

Best practice – implementing a collection view in Backbone.js


Lately I was working a lot with Backbone.js, I really love this tool! It is so easy to encapsulate my code into separate components.

What I had a lot of thought about but with no real answer is what is the best way to implement a collection view?

As I see it there is mainly two ways to approach this:

  1. Implement the model with a model view and the collection view will just be the container that contain all the model views.
  2. Implement the collection view to render also the models in it.

Each of these approaches has upsides and downsides. And the difference is really the question of where to render the model? in the model view? or in the collection view? the intuition is to do it in the model view – but that is making a few disadvantages of interaction between the models.

The downside I have with the 2nd approach is that for any addition / subtraction from the collection the entire collection view (with all the models) will need to re-render, in a collection with thousands of models – that is a huge problem! But it has an upside too – if the models have some kind of interaction between them (sorting, filtering) it is much more easy to implement it in the 2nd approach.

The downside of the 1st approach is the upside of the 2nd and vice a versa. So I could say that I should select the solution according to my needs, and that is what I did until now. Until the day that I needed both upsides…

So the question is – is there a way to implement the 1st approach but to also have the ability to have sorting and filtering on the UI? The only way I could think about that happening is that the collection view will also hold all of the model views but that just does not sounds right…

Go with the Model-View approach

Well, it is the combination of both that solves this problem. How can it be both? it is actually the first approach, each model has it’s own model view, so adding to the collection will not need to render the entire collection view. Only when we want to sort / filter – the entire collection view will be re-render.


This solution is really a best practice since the models does not know about the sorting / filtering that can be made to them – this will be implemented in the collection and the final visual result will be rendered in the collection view

Untitled drawingSo when we want to render all the models that a ‘filter’ function returned us. we will run on each model and we will create it a model view and then we will append all the model views to the collection view.


SVN Vs Git

gitLogo Well, we know why we should use a VCS (Version Control System) is a great thing to have, but there are a lot of VCS systems out there. How to choose one from all the variety there is out there?
I will not say which is the best one because I have experience in SVN (Subversion) and Git and not in every VCS there is out there, so I’m going to compare just these two. They are also currently the most popular ones.

svnLogoLet’s start with the conclusion – In my opinion Git is better than SVN. I also talked about it with other people from the industry and they all concluded that Git is better, some of them still use SVN but that is only because it is a huge deal for them to perform the migration from SVN to Git.

Let’s go into the Why’s:

Locale repository

The repository, the system that hold all the changes that were made to the files, in Git it is not only on the main repository on a remote server it is also in my local copy – that mean that if from some reason my server is gone – anyone that fetched data from the server – has a copy of the repository. that is a great backup repository strategy, all you need for that is to be updated.

Local commit

This is a huge advantage! It’s not only for the times that you are on a train without internet connection. When you work on a project you code almost everyday. sometimes there is an internet glitch and you will be stuck without a connection – if you are using SVN, you can’t commit so you will have to choose between two options :

  • stop working until the connection is back
  • keep on working but then you need to make the commit of a bigger changes, that mean that “task separated commits” can go wrong this way.

In Git – you can just do a local commit and then push all the commits at once.
It is a good solution for when the repository is from some reason not accessible.

Built to branch

In Git branching is easy and natural, it takes seconds to create a branch and it is encouraged to branch before starting to work on anything. By branching (which is also possible on SVN, just less convenient…) I save myself the problem of leaving a current half baked work, starting a more urgent one without the half baked work and when finished going back to the half baked and resuming the work. with the option to also include the last more urgent task! How great is that? Merging branches is as easy as creating branches and once starting using branches in Git I feel the peace of mind of not screwing someone elses work.

As I have said in the beginning – I’m pro-Git. I really like it and have very happy experience with it. It’s not that SVN sucks, I just think that Git is a lot better.