Saturday, July 23, 2016

You don't know Javascript (Scope and Closure)

Javascript is one of the 3 main core technologies in world wide web. Since it's origin 2 decades back, it has evolved a lot and as per today, it is the trendiest programming language on earth.

Since 2009 I have used javascript to do web development and until recently I used it with basic dom manipulations with jquery, simple UI logic with vanilla JS and with some frameworks as AnuglarJS. The basic knowledge I had about JS was sufficient enough to get above things done. But recently when I started doing some serious development with React and GraphQL, I realized that my knowledge on JS is pretty primitive and I'm not really applying any core JS concepts or patterns in my code. At the same time, while I was listing to a podcast in Software Engineering Daily I found Kyle Simpson was explaining about series of his books called "You Don't know Javascript". With that, I got the interest in reading the book to sharpen my saw in JS. It's a pretty interesting book and it covers many basic concepts in JS. Following series of articles will cover what I learned in each of 
these books.


The scope is one of the core concepts in Javascript and it's a must to have a thorough understanding of the scope to write better JS code. Let's dig in further to scope.

What is scope?

The scope is set of well-defined rules on how to store and retrieve variables in a program. In one way or other, you are always dealing with these rules when writing and execute code in JS. 

In JS assignment for the scope can be performed in two ways.

1) by using = expression

a = 3;

2) or by passing an argument to a function parameter.

function foo(x) {


Lexical Scope

In JS, the scope is defined by Lexical Scope. Lexical Scope is defining the scope at author time based on where the functions are placed.

But there are two other ways to overwrite the lexical scope in JS. Those are JS core functions which will manipulate the scope at runtime. Those are,

1) eval() function
Eval function takes a string as an input and executes the content in the scope of the code execution.

2) with() function
Takes an object as the input and consider the object as a new separate lexical scope.

function foo(obj) {
foo({x:5}); // will print "5"

Cheating lexical scope makes the code performance intensive so better to avoid it.

Nested Scopes

In JS we can define different levels of scopes. The most outer scope is global scope and new scopes will be defined as nested scopes when we are creating functions or blocks.

var a = 5;

function foo(x) {
  var b = 10;
In above example "a" is in global scope and "b" is in a new function scope.

When Javascript engine finds a variable in an inner scope engine starts searching for it in the given scope and if it isn't there, it checks the variable in the immediate outer scope and likewise it traverse until it finds the variable and returns it. Once it reaches the most outer scope, it automatically stops traversing.

There is a really tricky part in how the fall back happens when the engine cannot find a defined variable in any given scope. If a variable is not found in any parent scope and if it's for an assignment purpose, then a new variable will be created in the global scope. You should be really careful on this.

var a = 5;

function foo(x) {
  b = 10;

When Javascript engine finds a variable in an inner scope engine starts searching for it in the given scope and if it isn't there, it checks the variable in the immediate outer scope and likewise it traverse until it finds the variable and returns it. Once it reaches the most outer scope, it automatically stops traversing.

Note: Global variables are automatically being part of the global object. In browser, it's the window object. So you can create global variables as "window.a". Using this technique you can access the variables in the global scope without getting affected from shadowing. Ex:

var a = 5;

function foo() {
  var a = 10;
  console.log(a); // will print "10"
  console.log(window.a); // will print "5"


This will print two lines as follows.


There is another interesting point demonstrated in the above example. It's shadowing.


Overriding the outer scope variables in inner scopes. Shadowing is commonly used in JS which allows developers to isolate variables within functions while using same variable names.

Since scope is really powerful as well as dangerous when misusing it, there are identified best practices to avoid surprises. All these best practices are targeting common objectives such as avoiding spoiling global scope, isolate variables in function scope as much as possible. Following are some of such best practices.

Isolate in objects

It's a best practice to create an object in the global namespace and define variables and functions as properties of the object. In this way, we will only define a limited number of variables in the global scope and all the other variables will be properties of carrier objects.

var myLibrary = {
  foo: function() {
    console.log('this is foo');
  x: 5
}; // will print "this is foo"

Module Managment

Most of the modern JS libraries wraps its variables in a module and expose via dependency management. When using these libraries in code, we have to import scope into another object scope which will prevent spoiling the global scope. 

Will be covered more under Closure section.

Functions as Scope

When we have named functions, it pollutes the global name space. That can be avoided with following technique by treating function as an expression rather than a declaration.

(function foo() {
    console.log('How are you');
})(); // will print "How are you"

Also you can pass a variable into the function as follows.

(function foo(x) {
})("Hi"); // will print "Hi"

In above code first () make the function an expression and second () execute the expression.

Anonymous vs Named functions

Function expression can be anonymous but function declaration cannot be anonymous. It's prefer to have named function which has less drawbacks than anonymous functions. 

Following are valid syntaxes because there the function is an expression.

var x = function(x) {

x('wow'); // will print "wow"

(function(x) {
)('wow'); // will print "wow"

Following syntax is invalid because the there we use a function declaration.

function(x) {

Blocks as Scope

Generally if we define a variable with var keyword it belongs to the scope beyond the block and applicable for the whole scope.

if (true) {
  var n = "How are you";

console.log(n); // will print "How are you"

In above code variable "n" will belong to global scope. That happens becuase of variable hoisting in JS engine.

Variable Hoisting

Variables and function declarations are move to the top of the scope block. In here subsequent function declarations will override the previous.

a = 2;
var a;
console.log(a) // will print 2

console.log(a); // will print undefined
a = 2;
var a;

But if you define a variable with "let" keyword, it'll only belong to the current block. Variable declarations with "let" keyword will not effect to variable hoisting.

if (true) {
  let m = "How are you";

console.log(m); // will give an error

You can create a constant variable using const keyword and it's scope will be limited to the current block.

if (true) {
  const m = "How are you";
  m = "Changed"; // will give an error



What is Closure?

Closure is when a function is able to remember and use it's lexical scope even when the function is executing outside of the lexical scope.

Closure is one of the least understood features  in JS, but it is one of the most powerful features in JS. 

function foo(a)
  function bar() {
  return bar;

var baz = foo(2);
baz() // will print 2

In above example, "bar" still has the reference to the scope of a function, and that reference is called closure.

Closure is heavily used in JS programming all over the programs. One of it's main application is there when developers create modules to isolate and expose variables and functions to outside.


Function return an object with references for internal functions. Those function will run outside the defined lexical scope and it's a good example for a closure.

function myModule(a, b) {
  function sum() {
    return a +b;

  function substract() {
    return a - b;

  return {
    sum: sum,
    substract: substract

var operations = myModule(2, 4);
operation.sum() // Will print 6

This is a great way to keep the global scope clean as well expose necessary components to outside while maintaining an internal state of the module.

Now we have come to the end of this article about Javascript Scope and Closure concepts. Hope you got some quick interesting points about them and if you need further readings it's highly recommend to read the series of  "You Don't know Javascript" books. I'll bring some more interesting points in my next article about Javascript Objects and Prototyping. 


  1. wow i just stumbled with your explanation here. And i am interested to know more like this. So please keep update like this.

    Email Marketing Chennai

  2. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.

    web designing training in chennai

  3. Very nice post here and thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.
    IELTS Coaching in Chennai

  4. Such a great articles in my carrier, It's wonderful commands like easiest understand words of knowledge in information's.

    AWS Training in Chennai

  5. Finding the time and actual effort to create a superb article like this is great thing. I’ll learn many new stuff right here! Good luck for the next post buddy..
    SEO Company in Chennai

  6. Great.. Tutorial is just awesome..It is really helpful for a newbie like me...

    JavaScript Online Training JavaScript Online Training JQuery Online Training JQuery Online Training
    JavaScript Course | HTML5 Online Training

  7. I have read your blog its very attractive and impressive. I like it your blog.

    Javascript Training in Chennai | HTML5 Online Training

  8. Thank you for sharing such a nice and interesting blog with us. I have seen that all will say the same thing repeatedly. But in your blog, I had a chance to get some useful and unique information. I would like to suggest your blog in my dude circle.
    Jobs in Chennai
    Jobs in Bangalore
    Jobs in Delhi
    Jobs in Hyderabad
    Jobs in Kolkata
    Jobs in Mumbai
    Jobs in Noida
    Jobs in Pune

  9. Wonderful bloggers like yourself who would positively reply encouraged me to be more open and engaging in commenting.So know it's helpful.
    PTE Coaching in Chennai

  10. Great post! I am see the programming coding and step by step execute the outputs.I am gather this coding more information. It's helpful for me my friend. Also great blog here with all of the valuable information you have.

    Fresher Jobs in Mumbai
    Fresher Jobs in Pune
    Fresher Jobs in Noida
    Fresher Jobs in Hyderabad

  11. I am not sure the place you are getting your information, however good topic.I needs to spend some time studying more or understanding more.Thank you for wonderful information I was in search of this info for my mission.

    HR Consultancy in Chennai
    Recruitment Consultancy in Chennai
    Manpower Consultancy in Chennai

  12. This is extremely helpful info!! Very good work. It is very interesting to learn and easy to understood. Thank you for giving information. Please let us know and more information get post to link.

    Digital Marketing Company in Chennai

  13. you are posting a good information for people and keep maintain and give more update too.
    seo company in india

  14. Its a wonderful post and very helpful, thanks for all this information. You are including better information regarding this topic in an effective way.Thank you so much

    Personal Installment Loans
    Title Car loan
    Cash Advance Loan

  15. For beginners and also for intermediate in javacript this blog is really helpful as it mainly focuses on scope and types and also functions.

    Digital Marketing Company in India

  16. i really like this blog.And i got more information's from this blog.thanks for sharing!!!!
    Web Design Company in Chennai

  17. It’s the best time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I want to suggest you few interesting things or suggestions.You can write next articles referring to this article. I desire to read even more things about it..
    SAP HR Training in Chennai
    SAP ABAP Training in Chennai
    SAP FICO Training in Chennai

  18. Great articles, first of all Thanks for writing such lovely Post! Earlier I thought that posts are the only most important thing on any blog. But here at

    Shout me loud I found how important other elements are for your blog.Keep update more posts..

    cloud computing training in chennai

  19. Excellent goods from you, man. I’ve understand your stuff previous to and you’re just too excellent. I actually like what you’ve acquired here, certainly like what you are stating and the way in which you say it. You make it enjoyable and you still take care of to keep it sensible. I can not wait to read far more from you. This is actually a tremendous site..
    Pimple Treatment
    Pigmentation Cream
    Acne Cream

  20. There are lots of information about latest technology and how to get trained in them, like this have spread around the web, but this is a unique one according to me. The strategy you have updated here will make me to get trained in future technologies. By the way you are running a great blog. Thanks for sharing this.
    Web development Company in India

  21. This blog is having the general information. Got a creative work and this is very different one. We have to develop our creativity mind. This blog helps for this. Thank you for this blog. This is very interesting and useful.

    Self Employment Tax
    Tax Preparation Services
    Tax Accountant
    Tax Consultant
    Tax Advisor

  22. This is very important for web designers perfection is most important. This article contains some of the most informative content. I think much like this writer. It is a very valuable and helpful collection of blogs.
    development Company in India

  23. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic.

    Eczema Treatment

  24. i really like this blog.And i got more information's from this blog.thanks for sharing!!!!
    Best Interior Designers in Chennai

  25. This is a great article, I have been always to read something with specific tips! I will have to work on the time for scheduling my learning.
    Hadoop Training in Chennai

  26. I appreciate your style of writing because it conveys the message of what you are trying to say. It's a great skill to make even the person to understand the subject . Your blogs are understandable and also informative. I hope to read more and more interesting articles from your blog. All the best.
    Psoriasis Treatment

  27. Thank you for your is very useful for me .keep more updates.waiting for your new blog.
    Business Tax Return
    Cpa Tax Accountant
    Tax Return Services

  28. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic.

    Eczema Treatment
    Psoriasis Oil
    Hyperpigmentation Treatment
    Herbal Tonic

  29. Really i like this blog and i got lot of information's from your blog.And thanks for sharing!!!!
    Human resources management software
    cctv camera installation in Chennai
    RFID Solutions

  30. Very nice post here thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.
    Business Tax Return
    Cpa Tax Accountant
    Tax Return Services

  31. Just read your website. Good one. I liked it. Keep going. you are a best writer your site is very useful and informative thanks for sharing!
    Herbal Shampoo
    Dandruff Treatment

  32. I must thank you for the efforts you have put in spending this site. I am hoping to out the same high-grade content by you later on as well. In truth, your creative writing abilities has inspired me to get my own, personal blog now..
    Java Training in Chennai
    Dot Net Training in Chennai
    Cloud Computing Training in Chennai
    Digital Marketing Training in Chennai
    SAS Training in Chennai
    SEO Training in Chennai
    AWS Training in Chennai
    Microsoft Azure Training in Chennai

  33. Its a wonderful post and very helpful, thanks for all this information. You are including better information regarding this topic in an effective way.Thank you so much
    Wooden Temple for Home
    Tanjore Painting
    Pooja Mandir

  34. I have really enjoyed reading your blog..very interesting and unique informative post..your writing is good..keep on updates.Thanks for sharing for this information.

    SAP Training Institute in Chennai
    SAP HR Training in Chennai
    SAP SD Training in Chennai
    BEST SAP BASIS Training in Chennai

  35. Really it was an awesome article...very interesting to read..You have provided an nice article....Thanks for sharing..
    Android Training in Chennai
    Ios Training in Chennai

  36. Its a wonderful post and very helpful, thanks for all this information. You are including better information regarding this topic in an effective way.Thank you so much.
    Welding Inspection course in Chennai
    NDT Jobs in Chennai

  37. These ways are very simple and very much useful, as a beginner level these helped me a lot thanks fore sharing these kinds of useful and knowledgeable information.

    Selenium Training in Chennai

  38. Great.Nice information.It is more useful and knowledgeable. Thanks for sharing keep going on..
    SEO company in India

  39. Thanks for sharing, Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this.
    SEO Company in Chennai

  40. This is so informative blog and i have used this 5 minutes thing very useful too happy with this blog........

    MSBI Training in Chennai
    Base SAS Training in Chennai
    Hadoop Training in Chennai

  41. i have really enjoyed sharing your website. thank you so much for your sharing this document. this document more useful and improve our knowledge.
    salesforce training in chennai

  42. Its really very useful topic. Thanks for sharing this information...

    SAP FICO Training in Chennai


  43. This is so informative blog and i have used this 5 minutes thing very useful too happy with this blog........
    SAP FICO Training in Chennai

  44. It is a very useful and informative blog. Keep on sharing like this information...
    SAP MM Training in Chennai

  45. A great content and very much useful to the visitors. Looking for more updates in future.

    PYTHON Training in Chennai

  46. I gain lot of information from this article........thank you
    Cloud computing certification in chennai

  47. This is very nce one.. really spend time with good thing.... i will share this to my frends...thank you so much for this post....
    waiting for the next blog.....


  48. It is really a great and useful piece of info. I’m glad that you shared this helpful info with us. Please keep us informed like this. Thank you for sharing.

    Best Interior Designers in Chennai
    Industrial Architecture
    Warehouse Architect
    Factory Architect Chennai

  49. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.

    Manufacturing ERP
    Human Resources Management Software
    CCTV Camera Dealers in Chennai

  50. Thanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.

    Wellnesscentres in Chennai
    Weightloss in Chennai
    Weightgain in Chennai

  51. Indian Cyber Army’s summer internship is live now. Here internship will give you on-the-job experience, help you learn whether you and Cyber security industry are a good match and can provide you with valuable connections and references. Here interns are usually exposed to a wide variety of tasks and responsibilities which allows the intern to showcase their strengths by working on projects for various managers that work on different parts of Indian Cyber Army. Start your career in ethical hacking by working with Indian cyber army.

  52. Thanks for the information.It is really nice .Information security is the set of processes that maintain the confidentiality, integrity and availability of business data in its various forms.In this age of Technology advancement, computer and information technology have not only brought convenience to citizens in modern life but also for policemen & various Government officials of the nation to fight cybercrime through various modus operandi. Indian Cyber Army has been dedicated in fighting cyber crime, striving to maintain law and order in cyberspace so as to ensure that everyone remains digitally safe.Read more:- Information Security

  53. What you have written in this post is exactly what I have experience when I first started my blog.I’m happy that I came across with your site this article is on point,thanks again and have a great day.Keep update more information.
    Research Paper Publication
    Science Journal
    IEEE Projects
    Journal Impact Factor
    Highest Impact Factor Journal

  54. thanks for sharing the more valuable information.
    Indian Cyber Army credibility in Ethical hacking training & Cybercrime investigation training is acknowledged across nation as we offer hands on practical knowledge and full assistance with basic as well as advanced level ethical hacking & cybercrime investigation courses. The training is conducted by subject specialist corporate professionals with wide experience in managing real-time ethical hacking/ cyber security projects. Indian Cyber Army implements a blend of academic learning and practical sessions to give the candidate optimum exposure.Ethical hacking training ,
    Ethical hacking course

  55. To maximize impact of RPA, identify impactful processes. These processes tend to be Impacting both cost and revenues , High volume , With low fault tolerance , Error prone , Speed-sensitive , Requiring irregular labor , Distributed processes that require coordinated efforts of multiple departments ,Select processes that can be easily automated with RPA. Such processes tend to be
    Rules based
    Not on the roadmap for new systems
    Robotic Process Automation RPA training in chennai