Skip to main content

JavaScript Scope

In this blog post we will dig deeper into various aspects of JavaScript scope.  This is a pretty interesting topic  and also a topic which confuses many beginning JavaScript programmers.

Understanding JavaScript scope helps you write bug free programs (hmm.. atleast helps your troubleshoot things easily)

Scope control the visibility and lifetimes of variables and parameters.  This is important from the perspective of avoiding naming collisions and provides memory management service.

Unlike other languages, JavaScript does not have block level scope.  For e.g. take for instance the following piece of c# code.
public void Main () {
int a = 5;
if (true) {
int b = 10;
}
// This will throw compile time error as b is not defined
// and not within the scope of function Main();
Console.WriteLine(b);
}

If you write the same code in JavaScript, then the value of 'b' will be available outside the 'if' block. The reason for this is JavaScript does not have block level scope. Scopes works at the function level and because of a feature called 'hoisting' all variable declaration in JavaScript is moved to the top of the function.

You can read more about hoisting here http://rajeshpillai.tekacademy.com/hoisting/
function scopeDemo() {
var a = 5;
if (true) {
var b = 10;
}
// This will work even though 'b' is defined inside if block because of 'hoisting'
alert(b);
}

scopeDemo(); // Invoke the function

Remember, Scope in JavaScript is at function level and not block level.

So, contrary to popular guidelines of most programming lanaguage to declare variables as late as possible, in JavaScript it is recommended to declare all your variables as early as possible.


Happy Scoping !!!


You can try out the demo here

Comments

Amos said…
Where exactly is the facebook like button ?
Susan said…
A better magazine theme would make the blog nicer.:)
What's up to every single one, it's genuinely a nice for me to go to see this web site, it contains valuable Information.
Funny Pix said…
Hello, all the time i used to check blog posts here early in the dawn,
because i enjoy to gain knowledge of more and more.
Just about all emotions and idealogy aside, I think it's the potential to be your greater works, may you keep producing this type of quality within your future writing. Thanks so much.
boko said…
Two-bit peach on:
http://shop.xaijo.com/?new-qz.html

behalf executive topics physical feeding discovery averages kerr fosamaxd authenticity brief spite pursuant anafranil inflammation suite zostrix boxes sheet stanley headaches coconut protozoa fagerstrom flows

http://intimcity.org/in.htm?profile-wl&wm=2020890811
Visit Indonesia said…
There was clearly this time when i had been bored to death browsing other's thoughts and mind through their blog site. But just before long once i got right here on your posts, the passion of reading and also smiling on some people's daily post appears to come back, my personal curiosity has peaked once again all thanks to you mate. I think you will continue this for some time. Excellent job my friend.
Visit Indonesia said…
what's up...

I really loved reading your post. Thanks!A field nearby to my nerve cheers, do you have a RSS graze ?...
Antony Respicio said…
Spot on with this write-up, I actually suppose this web site wants way more consideration. I’ll most likely be again to read much more, thanks for that info.
Visit Indonesia said…
peace be upon you...

I can see you have high standards when it comes to your writing. It shows in your excellent writing. Thank you for your high standards....
how you doin...

In this awesome pattern of things you actually secure a B- with regard to effort and hard work. Exactly where you actually confused me was first in your facts. As as the maxim goes, the devil is in the details... And that could not be more accurate her...
nice job...

I do not usually find this type of data interesting, but you have proven that a talented writer can take information that is often considered dull and make it pop....
peace be upon you...

I can see you have high standards when it comes to your writing. It shows in your excellent writing. Thank you for your high standards....
ubud bali said…
nice job...

I do not usually find this type of data interesting, but you have proven that a talented writer can take information that is often considered dull and make it pop....
jasa seo said…
hello buddy!...

My spouse and I stumbled over here from a different page and thought I might as well check things out. I like what I see so i am just following you. Look forward to going over your webpage repeatedly....
boko said…
At large shipping betray:
http://shop.xaijo.com/?new-wo.html

inefficiency unreliable demo tveyes burn asserted ceftin orderpharma epsos container suits booklet unimportant naspa responsive until acquired going submissions codenob strives network lucarotti scholarship eprescribing

http://intimcity.org/in.htm?profile-oc&wm=2020890811
http://search.erolove.in/?new-rb.html
http://blog.erolove.in/land?browse-em.html
Donn Celi said…
I simply want to tell you that I'm all new to blogging and honestly loved this blog site. Almost certainly I’m likely to bookmark your blog . You amazingly have great stories. Thanks a lot for sharing with us your blog.
Karena Mooe said…
Sharing some thing is better than keeping up-to our self, so the YouTube video that is posted here I am going to share with my relatives and colleagues.
This is the proper weblog for anybody who needs to find out about this topic. You understand so much its virtually hard to argue with you (not that I really would need…HaHa). You undoubtedly put a brand new spin on a topic thats been written about for years. Great stuff, simply great!
Eldon Jupiter said…
The Zune concentrates on being a Portable Media Player. Not a web browser. Not a game machine. Maybe in the future it'll do even better in those areas, but for now it's a fantastic way to organize and listen to your music and videos, and is without peer in that regard. The iPod's strengths are its web browsing and apps. If those sound more compelling, perhaps it is your best choice.
sesli sohbet said…
Thank you for the good writeup. It if truth be told was a leisure account it. Look advanced to more brought agreeable from you! However, how could we be in contact?
sesli sohbet said…
I was studying some of your content on this site and I believe this web site is very informative ! Continue putting up.
sesli sohbet said…
I like this web blog very much so much great information. “Probably the most distinctive characteristic of the successful politician is selective cowardice.” by Richard Harris.
I discovered your blog website on google and examine a few of your early posts. Proceed to maintain up the superb operate. I just further up your RSS feed to my MSN News Reader. Seeking ahead to studying more from you later on!…
bayan escort said…
Zune and iPod: Most people compare the Zune to the Touch, but after seeing how slim and surprisingly small and light it is, I consider it to be a rather unique hybrid that combines qualities of both the Touch and the Nano. It's very colorful and lovely OLED screen is slightly smaller than the touch screen, but the player itself feels quite a bit smaller and lighter. It weighs about 2/3 as much, and is noticeably smaller in width and height, while being just a hair thicker.
Leland Zadrozny said…
I simply want to mention I am just new to blogging and site-building and seriously loved this page. Likely I’m likely to bookmark your website . You amazingly have remarkable article content. Kudos for sharing your web site.
You can definitely see your enthusiasm in the article
you write. The arena hopes for more passionate writers such as you who
aren't afraid to say how they believe. At all times go after your heart.

Popular posts from this blog

JavaScript Function Spaghetti Code

In this post we will have a look at the spaghetti code created by functions and how to avoid them. First lets quickly go through why this is a cause of concern. Problems with Function Spaghetti Code Variables/ functions are added to the global scope The code is not modular There's potential for duplicate function names Difficult to maintain No namespace sense. Let's take for example the following set of functions and check whats the issue with them. // file1.js function saveState(obj) {     // write code here to saveState of some object     alert('file1 saveState'); } // file2.js (remote team or some third party scripts) function saveState(obj, obj2) {      // further code...     alert('file2 saveState"); } Now the problem here is if your application is using saveState() then the execution of saveState() which one to call is determined by the script loading.  The later script overrides same functions already defined by earlier script. F

JavaScript for Web and Library Developers

This is my first blog post on my home domain and in this series of posts I will explore various facets of JavaScript language that will help us become better programmers.  The idea is tear apart the language and understand how to use the features and build libraries like jquery, knockoutjs, backbonejs. The idea is not to replicate this libraries, but understand the inner workings using better JavaScript coding practices, design principles and thereby make the web a better place to visit.. We will be covering the following topics, though not in order and there may be addition to this list. Foundations Patterns Closure this keyword Hoisting Anonymous function Currying Server side JavaScript Canvas etc. Hope you will enjoy this journey with me!