What are Immediately-Invoked Function Expression ?

IIFE for short, This is the self-invoking anonymous function. It executes immediately after it’s created.


Defining IIFE
Syntax : (function(){…})()

The first pair of parentheses (function(){…})() turns the code within into an expression,
and the second pair of parentheses (function(){…})() calls the function that results from that evaluated expression.

This pattern is often used when trying to avoid polluting the global namespace,
because all the variables used inside the IIFE are not visible outside its scope.

Passing parameter to IIFE
Syntax : (function(obj){…})(object);

Here the  (function(obj){…})(object) is passed as a parameter and will be accessible within the function as (function(obj){…})(object).

JavaScript, jQuery interview questions & answers

Creating a jQuery popup with an overlay

Create a basic popup and overlay with minimal styling and without any additional settings using jQuery/HTML and CSS.


Creating Overlay using HTML and CSS : 
Overlay is a container with some translucent background color which cover the whole page and user is unable to click on any functional part of the site below it.

HTML

<div id="overlay"></div>

CSS

#overlay {
display:none; /*hidden on pageload*/
position:fixed; /*this will disable it from scrolling*/
width:100%; /*this will give the full width*/
height:100%; /*this will give the full height*/
z-index:999; /*this will keep it above all elements in the page*/
left:0; /*this will align it to the left*/
top:0; /*this will align it to the top*/
background:#000; /*this will give it a black background*/
}

Creating Popup using HTML and CSS : 

HMTL

<div class="popup" id="popup1">
<a href="#" class="close">X</a>
<p>
this is a demo popup
</p>
</div>

CSS

.popup {
display:none; /*hidden on pageload*/
width:200px; /*width of popup*/
height:200px; /*height of popup*/
padding:10px; /*padding for popup*/
background:#fff; /*background of popup*/
border:1px solid #000; /*border of popup*/
position:absolute; /*this will keep it relative to the body*/
z-index:9999; /*this will keep it above the overlay*/
top:50%; /*keep popup in center*/
left:50%; /*keep popup in center*/
margin-left:-110px; /*keep popup in center (it is the - total width / 2)*/
margin-top:-110px; /*keep popup in center (it is the - total height / 2)*/
}
.popup .close { /* close link*/
float:right;
color:#000;
text-decoration:none;/*remove underline from the close link*/
}
.popup p { /*popup text*/
padding:10px 0;
}

Creating button to trigger the popup with overlay :

<a href="#" class="displayPopup">Display Popup</a>

Creating Functionality using jQuery: 

$(function() { //document ready
$(".displayPopup").on("click", function() { //click event of the button
$("#overlay").fadeTo(100, .3); //this will show the overlay awith a crossbrowser transparency
$("#popup1").show(); // show popup1
return false; //disable event propogation (avoid addition of "#" to url)
})

$(".popup .close").on("click", function() { //click event of the close button in popup
$("#overlay").hide(); //hide overlay
$(".popup").hide(); //hide popup
return false; //disable event propogation (avoid addition of "#" to url)
})
})

Download code files

JavaScript documentation generator tools JSDoc, YUIDoc, Docco. Which is the best ?

JavaScript documentation generator tools JSDoc, YUIDoc, Docco

JavaScript Document Generator in short is an API which process the JavaScript file and generates documentation from comments in source using a syntax.

Last week I implemented some of the JavaScript Document Generators [JSDoc, YUIDoc, Docco], here are some of my findings :


 JSDoc
– Syntax is easy to understand and implement with lot of choices
– Generated document is simple with all the tags listed on right side of the page.
– Default template of document is not user friendly.
  – Tags [methods, properties, modules] are grouped in same structure
– Interlinking between the pages and tags is not that perfect, like on index page if I click a tag then it will navigate me to the JS file where it belong (which is right) but when I click the tag on that page then it will take me back to the index page.
– No search feature

Docco
– Very easy to implement
– It generates very simple document, comments on left side and JS file on right side.
– Use no syntax just write comment using “//” and it will pick it up and show on left side of the document.
– No interlinking
– No Search Feature

YUIDoc
– Syntax is easy to understand but I found that it was not that easy in implementation as in JSDoc. However I got used to it after couple of trials
– Generated document is very user friendly, great use of the page space.
– Search feature on the template is great.
– Interlinking is prefect.
– Title, logo, version etc of the Index page are configurable through options.

After implementing them and reviewing the generated document I can conclude that YUIDoc is the best of them however need some practice to get used to it 😉


References : 
https://github.com/jsdoc3/jsdoc
http://jashkenas.github.com/docco/
http://developer.yahoo.com/yui/yuidoc/

Javascript engine and Google V8

A JavaScript engine is specialized computer software which interprets and executes JavaScript and commonly used in web browsers.

Here is the list of the JavaScript engine’s used by major browsers :

Mozilla Firefox : SpiderMonkey, TraceMonkey (v3.5), JagerMonkey (v4), IonMonkey (v18), OdinMonkey (v22)
Google Chrome : V8
Opera : Futhark(v10.10),  Carakan(10.50), V8 (v14)
Safari : JavaScriptCore or Nitro

Among all Google’s V8 is the fastest one and here is a little info about it : 

The V8 JavaScript Engine is an open source JavaScript engine developed by Google for the Google Chrome web browser. At its core it is a JavaScript interpreter but it is being pushed very aggressively for performance. Recent benchmarks have put its speed ahead of PHP, Ruby and Python.

Features : 
It is high performance JavaScript engine written in C++.
It is fast as it compiles JavaScript directly into native assembly. while others interpret javascript to a bytecode to be executed. This means there is no interpretation.
It has the flexibility to be able to be used client or server side.
It can also be found in MongoDb (version 2), Node.js and many other powerful and popular applications.
It is open source so anyone can download the source code and develop a C++ or javascript application using the power of the V8.

Refrences : 
http://en.wikipedia.org/wiki/JavaScript_engine
http://en.wikipedia.org/wiki/V8_(JavaScript_engine)

How to attach event to element which execute only once?

Usually when we attach event to element, event functionality remains with the element till element gets removed but if we do not want to remove the element and want to run the event functionality only once. What to do ?


Answer is jQuery one() method.

This attaches a handler to an event for the element. The handler is executed at most once per element. In simple terms, the attached function will be called only once.

$(document).ready(function() {
    $(“#foo”).one(“click”, function() {
        alert(“This will be displayed only once.”);
    });
});​

Pageload optimization using jQuery CDN

First thing first : What is CDN?

A content delivery network or content distribution network (CDN) is a large distributed system of servers deployed in multiple data centers across the Internet.



What it does?

The goal of a CDN is to serve content to end-users with high availability and high performance.
A CDN caches static resources in distributed servers across a region or worldwide, thereby bringing resources closer to users and reducing round trip time.

Main problem a CDN solve is latency. The amount of time it takes for the host server to receive, process, and deliver on a request for a page resource (images, CSS files, etc.). Latency depends largely on how far away the user is from the server, and it’s compounded by the number of resources a web page contains.

Lets come to the topic : Which are the popular jQuery CDN?

There are 3 popular jQuery CDNs.
1. Google.

<script type=”text/javascript”    src=”http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js”>
</script>

2. Microsoft

<script type=”text/javascript”
    src=”http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js”>
</script>

3. jQuery.

<script type=”text/javascript”
    src=”http://code.jquery.com/jquery-1.9.1.min.js”>
</script>

How it optimize the page load?

It reduces the load from your server.
It saves bandwidth. jQuery framework will load faster from these CDN.
The most important benefit is it will be cached, if the user has visited any site which is using jQuery framework from any of these CDN.

How to load jQuery locally when CDN fails?

Given jQuery code checks whether jQuery is loaded from Google CDN or not, if not then it references the jQuery.js file from your folder.

<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js”></script>
<script type=”text/javascript”>
if (typeof jQuery == ‘undefined’)
{
  document.write(unescape(“%3Cscript src=’Scripts/jquery.1.9.1.min.js’ type=’text/javascript’%3E%3C/script%3E”));
}
</script>

It first loads the jQuery from Google CDN and then check the jQuery object. If jQuery is not loaded successfully then it will references the jQuery.js file from hard drive location. In this example, the jQuery.js is loaded from Scripts folder.

undefined and null in javascript. What is the difference ?

There is one difference between undefined And null in JavaScript undefined is a data type and null is a value.


undefined means a variable has been declared but has not yet been assigned a value, such as:

var TestVar;
alert(TestVar); //shows undefined
alert(typeof TestVar); //shows undefined


null is an assignment value. It can be assigned to a variable as a representation of no value:

var TestVar = null;
alert(TestVar); //shows null
alert(typeof TestVar); //shows object

Both of them are representing a value of a variable with no value

AND null doesn’t represent a string that has no value

Like

var a = ”; 
console.log(typeof a); // string 

var a = ”  ;
console.log(a == null); //false 
console.log(a == undefined); // false 

Now if

var a ;
console.log(a == null); //true
console.log(a == undefined); //true 

But

var a; 
console.log(a === null); //false 
console.log(a === undefined); // true

So each one has it own way to use

undefined use it to compare the variable data type

null use it to empty a value of a variable

var a = ‘javascript’;
a = null ; // will change the type of variable “a” from string to undefined 

Now it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

Event Bubbling, How to prevent it ?

Event bubbling and capturing are two ways of event propagation in HTML DOM.

In bubbling the event is first captured and handled by the inner most element and then propagated to outer elements.
In capturing the event is first captured by the outer most element and propagated to the inner most element.

Only event bubbling model is supported by all the major browsers.

If for some reasons you want to stop propagation, you should “capture” an event and stop it from going further.

preventDefault(), stopPropagation(), stopImmediatePropagation(), return false, all these 4 methods are used to cancel the event or prevent it from bubbling. But they all are different from each other, Here’s a tiny bit of explanation.

event.preventDefault() :
– This method stops the default action of an element from happening. For example, Prevents a link from following the URL.

event.stopPropagation():
– Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
– For example, if there is a link with a click method attached inside of a DIV or FORM that also has a click method attached, it will prevent the DIV or FORM click method from firing.
– Allows other handlers on the same element to be executed.

return false :
– It will do both ‘stops the default action of an element from happening’ and ‘Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.’

event.stopImmediatePropagation() :
– This method prevents every event from running.

For example, see below jQuery code block.

$(“p”).click(function(event){
  event.stopImmediatePropagation();
});
$(“p”).click(function(event){
  // This function won’t be executed
  $(this).css(“background-color”, “#f00”);
}); 

If event.stopPropagation was used in previous example, then the next click event on p element which changes the css will fire, but in case event.stopImmediatePropagation(), the next p click event will not fire.

parent, parents, closest. What is the difference ?

All these 3 jQuery methods are used for navigating upwards through the DOM. But they all are different from each other in ways that make them each uniquely useful, Here’s a tiny bit of explanation.

.parent()
– Matches the one immediate parent of the element(s)
– Optionally filtered by a selector.
eg:
<div class=”first”>
  <div class=”second”>
    <div class=”third”>
      <div class=”fourth”></div>
    </div>
  </div>
</div>
$(‘.fourth’).parent(); // this will select div with the class ‘third’ which is parent of the div with class ‘fourth’

.parents()
– It is not restricted to just one level above the matched element(s).
– It can return multiple ancestors.
– Optionally filtered by a selector.
eg.
<div class=”first”>
  <div class=”second”>
    <div class=”third”>
      <div class=”fourth”></div>
    </div>
  </div>
</div>
$(‘.fourth’).parents(); // this will return all the div elements which are parent of the div with class ‘fourth’

.closest()
– It works like parents(), except that it returns only one parent/ancestor.
– Get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
eg.
<div class=”first”>
  <div class=”second”>
    <div class=”third”>
      <div class=”fourth”></div>
    </div>
  </div>
</div>
$(‘.fourth’).closest(‘.second’); // this will return the div element with class ‘second’ which is one of the parent of div with class ‘fourth’

empty, remove, detach. What is the difference ?

jQuery provides various methods to remove elements from DOM. But they all are different from each other, Here’s a tiny bit of explanation.

empty() :
-This method is used to remove all the child elements from matched elements.

remove() :
-This method is used to remove all the matched element.
-This method will remove all the jQuery data associated with the matched element.

detach() : 
-This method is same as .remove() method except that the .detach() method doesn’t remove jQuery data associated with the matched elements.

remove() is faster than .empty() or .detach() method.

bind, live, delegate, on. What is the difference ?

All these 4 jQuery methods are used for attaching events to selectors or elements. But they all are different from each other, Here’s a tiny bit of explanation.

.bind() : 
– This is the easiest and quick method to bind events.
– But the issue with bind() is that it doesn’t work for elements added dynamically that matches the same selector.
– It only attach events to the current elements not future element.
– Has performance issues when dealing with a large selection.

.live() : 
– This method overcomes the disadvantage of bind(). It works for dynamically added elements or future elements.
– Due to its poor performance on large pages, this method is deprecated as of jQuery 1.7.
– Chaining is not properly supported using this method.

.delegate() : 
– The .delegate() method behaves in a similar fashion to the .live() method, but instead of attaching the selector/event information to the document, you can choose where it is anchored.
– It supports chaining.

.on() : 
– Since live() was deprecated with 1.7, so new method was introduced named “.on()”.
– This method provides all the goodness of previous 3 methods and it brings uniformity for attaching event handlers.

For more read here .