Interview Questions - jQuery


1. What is $() in jQuery library?    

Answer:
The $() function is an alias of jQuery() function, at first it looks weird and makes jQuery code cryptic, but once you get used to it, you will love it's brevity.

$() function is used to wrap any object into jQuery object, which then allows you to call various method defined jQuery object.

You can even pass a selector string to $() function, and it will return jQuery object containing an array of all matched DOM elements.

I have seen this jQuery asked several times, despite it's quite basic, it is used to differentiate between developer who knows jQuery or not.

2. Order these selectors in fastest to slowest:
- id (#myid),
- class (.myclass),
- tag (input)
   

Answer:


tag > id > class



Tag selectors are fastest in jQuery. It only needs to scan all tag names Ex. body, title, span, input

Id selectors need to scan all elements and their id property.

Class selectors scans all elements and their all properties.

Click here for more about optimization of selectors.

3. What is the difference between .empty(), .remove() and .detach() methods in jQuery?

Answer:

All these methods .empty(), .remove() and .detach() are used for removing elements from DOM but they all are different.

.empty(): This method removes all the child element of the matched element where remove() method removes set of matched elements from DOM.

.remove(): Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

.detach(): This method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.


4. What is the difference between event.stopPropagation and event.stopImmediatePropagation?

Answer:

event.stopPropagation() allows other handlers on the same element to be executed,
while event.stopImmediatePropagation() prevents every event from running. For example, see below jQuery code block.


1
2
3
4
5
6
7
8
$("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.

5. What are various methods to make ajax request in jQuery?

Answer:

Using below jQuery methods, you can make ajax calls.


  • load(): Load a piece of html into a container DOM
  • $.getJSON(): Load JSON with GET method.
  • $.getScript(): Load a JavaScript file.
  • $.get(): Use to make a GET call and play extensively with the response.
  • $.post(): Use to make a POST call and don't want to load the response to some container DOM.
  • $.ajax(): Use this to do something on XHR failures, or to specify ajax options (e.g. cache: true) on the fly.

6. Explain following jquery selectors.
. # |= *= ~= $ ^ : >

Answer:

7. What are Call and Apply in Javascript? - Most imp question for js devs

Answer:

In JavaScript, functions are objects. JavaScript functions have properties and methods.

call() and apply() are predefined JavaScript function methods. Both methods can be used to invoke a function, and both methods must have the owner object as first parameter.


1
2
3
4
5
6
7
8
function myFunction(a, b) {
   return a * b;
}
myObject = myFunction.call(myObject, 10, 2);
   // Will return 20
myArray = [10, 2];
myObject = myFunction.apply(myObject, myArray);
   // Will also return 20


Both methods take an owner object as the first argument. The only difference is that call() takes the function arguments separately, and apply() takes the function arguments in an array.

In JavaScript strict mode, the first argument becomes the value of this in the invoked function, even if the argument is not an object.

In "non-strict" mode, if the value of the first argument is null or undefined, it is replaced with the global object.

P.S. With call() or apply() you can set the value of this, and invoke a function as a new method of an existing object.


8. What is prototype property?

Answer:

The JavaScript prototype property allows you to add new properties to an existing prototype:


1
2
3
4
5
6
7
8
9
10
function Person(first, last, age, eyecolor) {
   this.firstName = first;
   this.lastName = last;
   this.age = age;
   this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
Person.prototype.name = function() {
   return this.firstName + " " + this.lastName;
};


Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.


9. Explain and contrast the usage of event.preventDefault() and event.stopPropagation(). Provide an example.

Answer:

Event.stopPropagation() stops an event from bubbling up the event chain, whereas event.preventDefault() only precludes the browser’s default action on that event from occurring, but the event still propogates up the event chain.

For example, consider the following code snippet:


1
2
3
4
5
6
7
8
// in this example, 'foo' is a div containing button 'bar'
$("#foo").click(function() {
   // mouse click on div 'foo'
});
$("#bar").click(function(e) {
   // mouse click on button 'bar'
   e.stopPropagation();
});


Due to the call to stopPropagation() in the button’s click handler, the event never propogates to the div so its click handler never fires.

It effectively stops parent elements from knowing about an event on their children.

In contrast, if you replaced the above call to stopPropagation() with a call to preventDefault(), only the browser’s default action would be precluded, but the div’s click handler would still fire.

(Note: Although the stopPropagation() and preventDefault() methods are mostly used in jQuery event handling implementations, they apply to plain JavaScript as well.)


10. Difference between onload() and document.ready() function used in jQuery?

Answer:

We can add more than one document.ready() function in a page.

we can have only one onload function.

Document.ready() function is called as soon as DOM is loaded.

body.onload() function is called when everything (DOM, images)gets loaded on the page.



10 jQuery Best Practise for javascript developers


1.Caching DOM Selectors  

Every time you select a DOM element using jQuery, you are instantiating a new jQuery object and forcing jQuery to search the DOM.
Instead of creating multiple jQuery instances and forcing jQuery to re-query the DOM for a particular element, you can cache your jQuery object in a variable this will improve performance.


?
1
2
3
4
5
6
7
8
9
10
11
// Stores the jQuery instance inside of a variable
var elem = jQuery("#elem");
// Set's an element's title attribute using it's current text
elem.attr("title", elem.text());
// Set's an element's text color to red
elem.css("color""red");
// Makes the element fade out
elem.fadeOut();


If you prefer the previous code snippet to be on one line, you can chain multiple jQuery methods together like this:

1
2
3
4
5
// Stores the live DOM element inside of a variable
var elem = jQuery("#elem");
// Chaining
elem.attr("title", elem.text()).css("color""red").fadeOut();

2.Unobtrusive DOM Scripting

Never include Javascript events as inline attributes. This practice should be completely wiped from your mind.

 Bad Code

?
1
<a onclick="doSomething()" href="#">Click!</a>
All Javascript behaviours should be included in external script files and linked to the document with a <script> tag in the head of the page. So, the anchor tag would appear like this:

 Good Code

?
1
<a href="#" class="doSomething">Click!</a>
And the Javascript inside the myscript.js file would contain something like this:
?
1
2
3
4
jQuery('a.doSomething').on("click",function( e ){
    // Do something here!
    alert('You did something, woo hoo!');
});
The .on() method in jQuery allows us to easily attach a click event to the result(s) of our selector. So the code will select all of the <a> tags of class “doSomething” and attach a click event that will call the function.

3.Avoid multiple jQuery(document).ready() calls   

Executing code only after the DOM has been fully created, or the page content being fully loaded, is a good way of executing scripts. But it's unnecessary to repeat $(document).ready() or $(window).load() for each script you want to run. Better to just use it only once, and put your code inside a function.
?
1
2
3
4
5
6
7
8
9
10
jQuery( document ).ready( function () {
  // all your code here
});
jQuery( window ).load( function () {
  // all your code here
});


4.Selector Optimization   

  • Your jQuery selector is read from right to left.
  • A class can belong to ANY element of your HTML page.
  • An ID must be UNIQUE in your HTML page.
  • The fastest way to find an element with Jquery is by ID, then by Tag element, then by Class.
    ?
    1
    jQuery('.myClass').something();
    jQuery will have to check every element in your page before to return a result. You have two options to make this selector better: add a tag element, or add an ID before your class. If the tag element is a div, and you have plenty of div in your page, it will definitely help, but if you can get an id, pretty close to your class, you'll be in a better shape!
    ?
    1
    jQuery('#myID .myClass').something(); //or $('ul.myClass').something();


5.jQuery Events   

jQuery has seen a lot of different ways to bind an event to an element. The latest ones are .live(), .bind(), .delegate() and .on(). A lot of people have wondered which one to use and why. The answer is simple: .on()!!
Since jQuery 1.7 the methods .live(), .bind() and .delegate() are implicitly calling the on() method of your jQuery. The method .on() has multiple behaviors based on how you are declaring it:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* The jQuery .bind(), .live(), and .delegate() methods are just one
   line pass throughs to the new jQuery 1.7 .on() method */
  
// Bind
jQuery( "#members li a" ).on( "click", function( e ) {} );
jQuery( "#members li a" ).bind( "click", function( e ) {} );
  
// Live
jQuery( document ).on( "click""#members li a", function( e ) {} );
jQuery( "#members li a" ).live( "click", function( e ) {} );
  
// Delegate
jQuery( "#members" ).on( "click""li a", function( e ) {} );
jQuery( "#members" ).delegate"li a""click", function( e ) {} );


6. Use === to Test Equality   

When testing equality, a lot of languages with syntax similar to JavaScript use the double equals operator (==). However, in JavaScript you should always use triple equals (===). The difference is in how equality is determined. A triple equals operator evaluates the two items based upon their type and value.


?
1
2
3
4
5
if(1 === '1'//Returns false
if(1 == '1'//Returns true
if(0 === ''//Returns false
if(0 == ''//Returns true

The first line would equal false because the number one does not equal the character 1. That is what we would expect. The double equals operator, on the other hand, will attempt to coerce the two values to be the same type before comparing equality. This can lead to unexpected results. In the second grouping, the result using the double equals would be true. That probably isn't what we were expecting.


7. Declare Variables Outside of the For Statement   

When executing lengthy "for" statements, don't make the engine work any harder than it must. For example:

 Bad Code

?
1
2
3
4
5
for(var i = 0; i < someArray.length; i++) {
 var container = document.getElementById('container');
 container.innerHtml += 'my number: ' + i;
 console.log(i);
}
Notice how we must determine the length of the array for each iteration, and how we traverse the dom to find the "container" element each time -- highly inefficient!

 Good Code

?
1
2
3
4
5
var container = document.getElementById('container');
for(var i = 0, len = someArray.length; i < len;  i++) {
   container.innerHtml += 'my number: ' + i;
   console.log(i);
}

8. Don't Pass a String to "SetInterval" or "SetTimeOut"   

Consider the following code:
?
1
2
3
setInterval(
"document.getElementById('container').innerHTML += 'My new number: ' + i", 3000
);
Not only is this code inefficient, but it also functions in the same way as the "eval" function would. Never pass a string to SetInterval and SetTimeOut. Instead, pass a function name.
?
1
setInterval(someFunction, 3000);

9. Use {} Instead of New Object()  

There are multiple ways to create objects in JavaScript. Perhaps the more traditional method is to use the "new" constructor, like so:

 Bad Code

?
1
2
3
4
5
6
var o = new Object();
o.name = 'Jeffrey';
o.lastName = 'Way';
o.someFunction = function() {
   console.log(this.name);
}
However, this method receives the "bad practice" stamp without actually being so. Instead, I recommend that you use the much more robust object literal method.

 Good Code

?
1
2
3
4
5
6
7
var o = {
   name: 'Jeffrey',
   lastName: 'Way',
   someFunction : function() {
      console.log(this.name);
   }
};

10. Don't use try-catch-finally inside performance-critical functions   

  • The try-catch-finally construct creates a new variable in the current scope at runtime each time the catch clause is executed where the caught exception object is assigned to a variable.
  • Exception handling should be done at as high level in the script where it does not occur frequently, for example outside a loop.
  • Or if possible, avoid try-catch-finally completely

     Bad Code

    ?
    1
    2
    3
    4
    5
    6
    7
    8
    var object = ['foo''bar'], i;
    for (i = 0; i < object.length; i++) {
       try {
          // do something that throws an exception
       catch (e) {
          // handle exception
       }
    }

     Good Code

    ?
    1
    2
    3
    4
    5
    6
    7
    8
    var object = ['foo''bar'], i;
    try {
        for (i = 0; i < object.length; i++) {
            // do something
        }
    catch (e) {
        // handle exception
    }