Closure in JavaScript through examples

javascript closureWhat is Closure?

A Closure is a named or anonymous function defined within the context of an object or any other function, which preserves and access to the context where it was declared.

To understand closure, it requires you to be familiar with basic JavaScript concepts, such as scope of variables and functions.

A closure is a named or anonymous function:
javascript closure
This is not a closure:

//Named function
function greetings() { //this is not a closure function.
    return ‘Howdy’;
}

//anonimous function
var greetings2 = function () { //this is not a closure function.
    return ‘Hello’;
}

greetings(); //Shows Howdy.
greetings2(); //Shows Hello.

Basically a closure function is a function that can access to the variables declared in the outer context, including global variables.

 

book

Book Tip

Speaking JavaScript: An In-Depth Guide for Programmers
Like it or not, JavaScript is everywhere these days—from browser to server to mobile—and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position.

Amazon

 

Closures in action.

Here is an example that will help you recognize when you need to use a Closure.

How to do it correctly.

Suppose you want to use a variable to count and want to create a function to increment the count variable.

var counter = 0;
function increase() {
    counter += 1;  // increment its current value.
    console.log(counter);
}

increase();
increase();
increase();

 // The counter is now equal to 3.

Here we have a solution, but has flaws; the counter variable is global, any script on the page would have access to it and could change it without calling the increase function .

We need to make sure that the counter variable is only modified by the increase function.

Therefore, move the definition of the variable inside the function, so no one can modify it without calling the function increase:

function increase() {
    var counter = 0;
    counter += 1; // increment its current value.
    console.log(counter);
}

increase();
increase();
increase();

// We expect the value of the count variable is 3, but it will be 1.

Now the counter variable is not accessible from the outside (now is protected), but this wong work properly because every time you call the function it will define the variable account.

We need to create an internal function to solve this:

var increase = (function() {
    var counter = 0;
    return function () {
        return counter += 1;
    }
 console.log(counter);
})(); //* IIFE Auto-invoked function.

increase();
increase();
increase();

// The counter is now equal to 3.

*IIFE Immediately Invoked Function Expression (see Encapsulation in JavaScript).

A common mistake

Here’s an example of misuse of Closure function. Suppose we have the following code:

function count() {
     var i;
     for (i = 1; i <= 3; i ++) {
         setTimeout (function () {
             console.log ('The count value is '+ i);
         }, 1000); // 1000 milliseconds = 1 second
     }
}
count();

And this is how you can solve it:

function count() {
     var i;
     function display(j) {
         return function () {
             console.log ('The counter value is ' + j);
         }
     };

     for (i = 1; i <= 3; i ++) {
         setTimeout (display(i), 1000);
     }

}
count();

I’m not going to explain in detail how this is solved, I’ll leave it to you, if you understand what happened then you understand JavaScript closure. 😉

Other references:

https://developer.mozilla.org/es/docs/Web/JavaScript/Closures
http://javascriptissexy.com/understand-javascript-closures-with-ease/
http://www.w3schools.com/js/js_function_closures.asp

AngularJs: Notes for a better performance

Performance notes for AngularJs 1.x:

angularjs performanceThis is a compilation of few tips that you can use to improve the performance of your Angular applications. I got some of this techniques from internet and others from my personal experience when working with large enterprise AngularJs applications.

Avoid $watch

-Try to avoid as much as possible the use of $watch because Angular uses dirty checking to keep track of all the changes in app. This means it will have to go through the collection of watcher to check if they need to be updated (call the digest cycle). If one of the watcher is relied upon by another watcher, Angular would have to re-run the digest cycle again, to make sure that all of the changes has propagated. It will continue to do so, until all of the watchers have been updated and app has stabilized.

-One-time binding syntax:

In newer versions of Angular (v1.3.0-beta.10+), use the one-time binding syntax {{ ::value }} where it makes sense

//try to avoid
<div>{{ vm.title }}</div>

// recommended
<hdiv>{{ ::vm.title }}</div>

Binding once removes the watcher from the scope’s $$watchers array after the undefined variable becomes resolved, thus improving performance in each dirty-check. Make sure you use this only when you don’t need to update the value through the application life cycle.

-Debounce the ng-model

If you know there is going to be a lot of changes coming from an ng-model, you can de-bounce the input.
For example if you have a search input like Google, you can de-bounce it by setting the following ng-model option: ng-model-options=”{ debounce: 250 }.
This will ensure that the digest cycle due to the changes in this input model will get triggered no more than once per 250ms. Also you can make the model updates when an event happen, e.g. on blur: ng-model-options=”{ updateOn: ‘blur’ }”
https://docs.angularjs.org/api/ng/directive/ngModelOptions

-Limit DOM filters

Filters are really simple to use, we insert a pipe, the filter name and we’re done. However, Angular runs every single filter twice per $digest cycle once something has changed. This is some pretty heavy lifting. The first run is from the $$watchers detecting any changes, the second run is to see if there are further changes that need updated values.
Here’s an example of a DOM filter, these are the slowest type of filter, preprocessing our data would be much faster. If you can, avoid the inline filter syntax.

{{ filter_expression | filter : expression : comparator }}

Angular includes a $filter provider, which you can use to run filters in your JavaScript before parsing into the DOM. This will preprocess our data before sending it to the View, which avoids the step of parsing the DOM.

$filter('filter')(array, expression, comparator);

 

-Avoid JavaScript expensive operations

The most expensive operation in JavaScript is add or remove elements from the DOM, maybe you wont notice a performance issue when you add or remove a few element, but it could be a problem if you have to remove or insert thousands in a large application.

-How to detect bad performance in AngularJs:

  • Benchmark functions using console.time. You can use the console.time to have a rough idea of how long a function takes to execute the code, you can read more about console.time here.
  • Use Batarang extension to detect performance issues, also you can us it to debug your Angular app in general.

 


 

Tips and good practices in general:

  • Design your directives with Angular in mind, try to avoid as much as possible the use of JQuery.
  • Everything related to DOM manipulation should be in a directive.
  • Avoid use the controller to do business logic, the purpose of controllers is binding data to your view. They should not contain any logic and merely communicate with your services.
  • Use services and /or factories to do business logic and call the Apis.
  • If possible, you should consider fetching your data before your view gets initialized. By doing so, you can ensure that necessary data is available as soon as the user get’s the page, you could accomplish that by using resolve in your routingProvider. See this article.
  • Extend directives by using Directive Controllers, you can place methods and properties into a directive-controller, and access that same controller from other directives. You can even override methods and properties through this relationship.
  • Don’t wrap element inside of $(). All AngularJS elements are already jq-objects.
  • Don’t do if (!$scope.$$phase) $scope.$apply(), it means your $scope.$apply() isn’t high enough in the call stack. Best Practice to run the cycle digest
  • Don’t create a new plugin without trying to discover, fork and pull request existing plugins first.

Basics Browser Console Object API

Browser console API

This article will be focused in the console object API available in Google Chrome, Mozilla Firefox, and later versions of Internet Explorer browser. We are going to cover few of them in this article, for a full list of available commands go to the References section at the bottom of this article .

The Console object is available in two places: the code and the browser’s JavaScript Console.
You probably already know of console.log in my opinion this is the most used command of the console object.

  • console.log

    – For basic logging, Use this to print in the browser’s console general string messages about actions taking place within the code, also you can print Objects, Arrays, etc..
    e.g:

    console.log("simple text"); //simple text
    
    var str = 'World';
    console.log("Hello", str); //Hello World
    
    var arr = ['val1','val2','val3','val4'];
    console.log(arr); //["val1", "val2", "val3", "val4"]
    
    var userName = 'jomendez'
    console.log("Authenticating user '%s'", userName); //Authenticating user jomendez
    

 

  • console.error

    – For logging errors in your code. I use console.error within error callbacks on AJAX requests and anywhere else an error might be thrown like a try{}…catch{}. While similar to console.log, this method also includes a stack trace where the error was thrown.
    javascript browser console error

 

     

    book

    Book Tip

    Speaking JavaScript: An In-Depth Guide for Programmers
    Like it or not, JavaScript is everywhere these days—from browser to server to mobile—and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position.

    Amazon

     

  • console.dir(object)

    – When you log a DOM element to the console it displays in an HTML format. To display the JavaScript representation you may  use the dir() method
    browser console dir

  • console.group(title)

    – This command is used to create a group of console logging commands it accepts an optional title parameter. To end the grouping just call grouEnd() see below.

    var userName = "jomendez", authenticated = false;
    console.group("Authentication phase");
    console.log("Authenticating user '%s'", userName);
    // place your authentication code here...
    if (!authenticated) {
      console.log("User '%s' is not authenticated.", userName)
    }
    console.groupEnd();
    

    browser console group

 

  • console.groupCollapsed()

    – Exactly the same as the above method, except for the fact the initial group is collapsed and not opened.

 

  • console.groupEnd()

    – This allows you to end the group defined above.

 

  • console.time(label)

    – The console.time() help you to measuring how long a portion of code can take to be excecuted, you must pass a string to the method to identify the time marker. When you want to end the measurement call console.timeEnd() and pass it the same string passed to the initializer. The console logs the label and time elapsed when the console.timeEnd() method fires.

    console.time("Measure Array");
        var array= new Array(1000000);
        for (var i = array.length - 1; i &gt;= 0; i--) {
            array[i] = new Object();
        };
    console.timeEnd("Measure Array");
    

    Result:
    Measure Array: 1923.457ms

 

  • console.timeEnd(label)

    –This allows you to stop the timer logging function and the elapsed time will be printed out,  see the code above.

 

  • console.table()

    – You can use console.table() to View structured data. With this you can view arrays objects, etc.

    function Person(firstName, lastName, age) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
    }
    
    var family = {};
    family.mother = new Person("Susan", "Doyle", 32);
    family.father = new Person("John", "Doyle", 33);
    family.daughter = new Person("Lily", "Doyle", 5);
    family.son = new Person("Mike", "Doyle", 8);
    
    console.table(family);
    

    browser console table

 

  •  console.clear()

    – You can use the console.clear() command to clear the browser console.

 

References:

You can find a full list for the console api for the most popular browsers, NodeJs and Firebug:
Chrome: http://developers.google.com/chrome-developer-tools/docs/console-api/
Firebug: http://getfirebug.com/wiki/index.php/Console_API
Firefox: http://developer.mozilla.org/en-US/docs/Web/API/console
Internet Explorer: http://msdn.microsoft.com/en-us/library/ie/hh772183.aspx
Node.js: https://nodejs.org/api/console.html
Safari: http://developer.apple.com/library/safari/documentation/AppleApplications/Conceptual/ Safari_Developer_Guide/Console/Console.html

Notes:

There is bug in Internet Explorer 9 where the console object is only defined if the developer tools were open at least once. That means that you get a Reference Error if you refer to console and the developer tools weren’t open before. As a work around, you can check if the console object exists before you call it.

How to do encapsulation in JavaScript

Encapsulation:

If you come from classical object-oriented languages like Java or C#, it might be a littler tricky to do encapsulation in JavaScript (hiding variables from the external scopes).

In this post we going to see tree ways to do encapsulation with JavaScript:

  1. IIFE (immediately Invoked Function Expression).
  2. Closures
  3. getters and setters Properties.
  4. The Revealing Module Pattern.

IIFE (immediately Invoked Function Expression)

First lets cover what an IIFE is:

In JavaScript we declare functions like this:

function myFunc(){
   console.log(myVar); // "Hello World"
}

And we call the function like this:

myFunc();

An IIFE is a combination of both in one, now, the more common and most used method to create an IIFE is with the parenthesis like this:

(function myFunc(){
   console.log("Hello World"); // "Hello World"
})();

There are other ways to create IIFE, you can accomplish this by using any of the following operators: !, +, -, ~.

!function myFunc(){
   console.log("Hello World"); // "Hello World"
}();

+function myFunc(){
   console.log("Hello World"); // "Hello World"
}();

-function myFunc(){
   console.log("Hello World"); // "Hello World"
}();

~function myFunc(){
   console.log("Hello World"); // "Hello World"
}();

Closures:

In JavaScript a variable scope is defined by the curly braces { } of an expression, for example a function:

function myFunc(){
   var myVar = "Hello World";
}
console.log(myVar) //undefined

myVar is not defined outside of the { } of the function, now notice that you can access a variable defined in the outter scope, like this:

var myVar = "Hello World";
function myFunc(){
   console.log(myVar) // "Hello World"
}

With those two concepts you can encapsulate variables and remove it from the global scope and protect your data. This helps prevent variables and function declarations from living longer than expected in the global scope, which also helps avoid variable collisions. Also When your code is minified and bundled into a single file for deployment to a production, you could have collisions of  global variables. If you adopt to use IFFE in every JavaScript file, it will protects you against both of these by providing variable scope for each file.

 

book

Book Tip

Speaking JavaScript: An In-Depth Guide for Programmers
Like it or not, JavaScript is everywhere these days—from browser to server to mobile—and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position.

Amazon

 

getters and setters Properties:

Why getters and setters can be used for encapsulation?
A: To limit access to an internal state of an object.

One of the advantages of properties is that you can have behavior in your fields, also limitate the field to be read only and/or write only.

var myObj = {
   get myVar() {
      return 'Using get';
   },
   set myVar(value) {
      console.log('Using set, value: '+value);
   }
};

Note: Up to IE 8, it doesn’t support get and set operators, instead you’ll have to use the __defineGetter__ and __defineSetter__ methods that can be found in Object.prototype.

var myObj = {
    myVar1: 'Hello',
    myVar2: 'World'
};

myObj.__defineGetter__('sayHello', function(){
    return this.myVar1 + ' ' + this.myVar2;
});

myObj.__defineSetter__('sayHello', function(value){
    console.log(value);
});

The Revealing Module Pattern

With this pattern we encapsulate and hide or reveal variable and functions in an object:

var myRevealingModule = (function () {
 
        var privateCountVar = 0;
 
        function privateFunctionIncrement() {
            privateCountVar++;
        }
 
        function publicFunctionStart() {
           return privateFunctionIncrement();
        }
 
        
        function publicGetCount(){
          return privateCountVar;
        }
 
	function publicIncrement(){
	  return privateFunctionIncrement()
	}
 
       return {
            start: publicFunctionStart,
            increment: publicIncrement,
            count: publicGetCount
        };
 
    })();

If you run the code above you’ll see that only the methods revealed in the return {…} are public see image below:

  return {
            start: publicFunctionStart,
            increment: publicIncrement,
            count: publicGetCount
        };

encapsulation revealing module pattern

Wrapping up

JavaScript is not an object oriented language, it is a functional language, but we can work around to have some of the goodies of the Object Oriented languages in JavaScript.

Those are some references for what in my opinion are two of the best JavaScript books I ever read (they are free):
http://speakingjs.com/es5/ 
http://addyosmani.com/resources/essentialjsdesignpatterns/book/

 

Thanks for reading :)