Jquery interview question and answer.

Q1. What is jQuery?
Ans: jQuery is fast, lightweight and feature-rich client side JavaScript Library/Framework which helps in to traverse HTML DOM, make animations, add Ajax interaction, manipulate the page content, change the style and provide cool UI effect. It is one of the most popular client side library and as per a survey it runs on every second website.

Q2. Why do we use jQuery?
Ans: Due to following advantages.

  • Easy to use and learn.
  • Easily expandable.
  • Cross-browser support (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+)
  • Easy to use for DOM manipulation and traversal.
  • Large pool of built in methods.
  • AJAX Capabilities.
  • Methods for changing or applying CSS, creating animations.
  • Event detection and handling.
  • Tons of plug-ins for all kind of needs.

Q3. How JavaScript and jQuery are different?
Ans: JavaScript is a language While jQuery is a library built in the JavaScript language that helps to use the JavaScript language.

Q4. Is jQuery replacement of Java Script?
Ans: No. jQuery is not a replacement of JavaScript. jQuery is a different library which is written on top of JavaScript. jQuery is a lightweight JavaScript library that emphasizes interaction between JavaScript and HTML.

Q5. Is jQuery a library for client scripting or server scripting?
Ans. Client side scripting.

Q6. Is jQuery a W3C standard?
Ans: No. jQuery is not a W3C standard.

Q7. What is the basic need to start with jQuery?
Ans: To start with jQuery, one need to make reference of it's library.
Q8. Which is the starting point of code execution in jQuery?
Ans: The starting point of jQuery code execution is $(document).ready() function which is executed when DOM is loaded.

Q9. What does dollar sign ($) means in jQuery?
Ans: Dollar Sign is nothing but it's an alias for JQuery. Take a look at below jQuery code. 
 Collapse | Copy Code
$(document).ready(function(){
});
Over here $ sign can be replaced with "jQuery" keyword. 
 Collapse | Copy Code
jQuery(document).ready(function(){
});
Q10. Can we have multiple document.ready() function on the same page?
Ans: YES. We can have any number of document.ready() function on the same page.

Q11. Can we use our own specific character in the place of $ sign in jQuery?
Ans: Yes. It is possible using jQuery.noConflict().

Q12. Is it possible to use other client side libraries like MooTools, Prototype along with jQuery?
Ans: Yes.

Q13. What is jQuery.noConflict?
Ans: As other client side libraries like MooTools, Prototype can be used with jQuery and they also use $() as their global function and to define variables. This situation creates conflict as $() is used by jQuery and other library as their global function. To overcome from such situations, jQuery has introduced jQuery.noConflict().
 Collapse | Copy Code
jQuery.noConflict();
// Use jQuery via jQuery(...)
jQuery(document).ready(function(){
   jQuery("div").hide();
}); 
You can also use your own specific character in the place of $ sign in jQuery.
 Collapse | Copy Code
var $j = jQuery.noConflict();
// Use jQuery via jQuery(...)
$j(document).ready(function(){
   $j("div").hide();
}); 
Q14. Is there any difference between body onload() and document.ready() function?
Ans: document.ready() function is different from body onload() function for 2 reasons.

  1. We can have more than one document.ready() function in a page where we can have only one body onload function.
  2. document.ready() function is called as soon as DOM is loaded where body.onload() function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page.
Q15. What is the difference between .js and .min.js?
Ans: jQuery library comes in 2 different versions Production and Deployment. The deployment version is also known as minified version. So .min.js is basically the minified version of jQuery library file. Both the files are same as far as functionality is concerned. but .min.js is quite small in size so it loads quickly and saves bandwidth.

Q16. Why there are two different version of jQuery library?
Ans: jQuery library comes in 2 different versions.

  1. Production
  2. Deployment
The production version is quite useful at development time as jQuery is open source and if you want to change something then you can make those changes in production version. But the deployment version is minified version or compressed version so it is impossible to make changes in it. Because it is compressed, so its size is very less than the production version which affects the page load time.

Q17. What is a CDN?
Ans: A content delivery network or content distribution network (CDN) is a large distributed system of servers deployed in multiple data centers across the Internet. The goal of a CDN is to serve content to end-users with high availability and high performance.

Q18. Which are the popular jQuery CDN? and what is the advantage of using CDN?
Ans: There are 3 popular jQuery CDNs.
1. Google.
2. Microsoft
3. jQuery.
Advantage of using CDN.

  • 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
Q19. How to load jQuery from CDN?
Ans: Below is the code to load jQuery from all 3 CDNs.

Code to load jQuery Framework from Google CDN
 Collapse | Copy Code
<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
Code to load jQuery Framework from Microsoft CDN
 Collapse | Copy Code
<script type="text/javascript"
    src="http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js">
</script>
Code to load jQuery Framework from jQuery Site(EdgeCast CDN)
 Collapse | Copy Code
<script type="text/javascript"
    src="http://code.jquery.com/jquery-1.9.1.min.js">
</script>
Q20. How to load jQuery locally when CDN fails?
Ans: It is a good approach to always use CDN but sometimes what if the CDN is down (rare possibility though) but you never know in this world as anything can happen.

Below 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.
 Collapse | Copy Code
<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.

Q21. What are selectors in jQuery and how many types of selectors are there?
Ans: To work with an element on the web page, first we need to find them. To find the html element in jQuery we use selectors. There are many types of selectors but basic selectors are:

  • Name: Selects all elements which match with the given element Name.
  • #ID: Selects a single element which matches with the given ID
  • .Class: Selects all elements which match with the given Class.
  • Universal (*): Selects all elements available in a DOM.
  • Multiple Elements E, F, G: Selects the combined results of all the specified selectors E, F or G.
  • Attribute Selector: Select elements based on its attribute value.

Q22. How do you select element by ID in jQuery?
Ans: To select element use ID selector. We need to prefix the id with "#" (hash symbol). For example, to select element with ID "txtName", then syntax would be,
 Collapse | Copy Code
$('#txtName')
Q23. What does $("div") will select?
Ans: This will select all the div elements on page.

Q24. How to select element having a particular class (".selected")?
Ans: $('.selected'). This selector is known as class selector. We need to prefix the class name with "." (dot).

Q25. What does $("div.parent") will select?
Ans: All the div element with parent class.

Q26. What are the fastest selectors in jQuery?
Ans: ID and element selectors are the fastest selectors in jQuery.

Q27. What are the slow selectors in jQuery?
Ans: class selectors are the slow compare to ID and element.

Q28. How jQuery selectors are executed?
Ans: Your last selectors is always executed first. For example, in below jQuery code, jQuery will first find all the elements with class ".myCssClass" and after that it will reject all the other elements which are not in "p#elmID".
 Collapse | Copy Code
$("p#elmID .myCssClass");
Q29. Which is fast document.getElementByID('txtName') or $('#txtName').?
Ans: Native JavaScipt is always fast. jQuery method to select txtName "$('#txtName')" will internally makes a call to document.getElementByID('txtName'). As jQuery is written on top of JavaScript and it internally uses JavaScript only So JavaScript is always fast.

Q30. Difference between $(this) and 'this' in jQuery?
Ans: this and $(this) refers to the same element. The only difference is the way they are used. 'this' is used in traditional sense, when 'this' is wrapped in $() then it becomes a jQuery object and you are able to use the power of jQuery.
 Collapse | Copy Code
$(document).ready(function(){
    $('#spnValue').mouseover(function(){
       alert($(this).text());
  });
});
In below example, this is an object but since it is not wrapped in $(), we can't use jQuery method and use the native JavaScript to get the value of span element.
 Collapse | Copy Code
$(document).ready(function(){
    $('#spnValue').mouseover(function(){
       alert(this.innerText);
  });
});
Q31. How do you check if an element is empty?
Ans: There are 2 ways to check if element is empty or not. We can check using ":empty" selector.
 Collapse | Copy Code
$(document).ready(function(){
    if ($('#element').is(':empty')){
       //Element is empty
  }
}); 
And the second way is using the "$.trim()" method.
 Collapse | Copy Code
$(document).ready(function(){
    if($.trim($('#element').html())=='') {
       //Element is empty
  }
}); 
Q32. How do you check if an element exists or not in jQuery? 
Ans: Using jQuery length property, we can ensure whether element exists or not.
 Collapse | Copy Code
$(document).ready(function(){
    if ($('#element').length > 0){
       //Element exists
  });
});
Q33. What is the use of jquery .each() function?
Ans: The $.each() function is used to iterate over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array.

Q34. What is the difference between jquery.size() and jquery.length?
Ans: jQuery .size() method returns number of element in the object. But it is not preferred to use the size() method as jQuery provide .length property and which does the same thing. But the .length property is preferred because it does not have the overhead of a function call.

Q35. What is the difference between $('div') and $('<div/>') in jQuery?
Ans: $('<div/>') : This creates a new div element. However this is not added to DOM tree unless you don't append it to any DOM element.
$('div') : This selects all the div element present on the page.

Q36. What is the difference between parent() and parents() methods in jQuery?
Ans: The basic difference is the parent() function travels only one level in the DOM tree, where parents() function search through the whole DOM tree.

Q37. What is the difference between eq() and get() methods in jQuery?
Ans: eq() returns the element as a jQuery object. This method constructs a new jQuery object from one element within that set and returns it. That means that you can use jQuery functions on it.

get() return a DOM element. The method retrieves the DOM elements matched by the jQuery object. But as it is a DOM element and it is not a jQuery-wrapped object. So jQuery functions can't be used.

Q38. How do you implement animation functionality?
Ans: The .animate() method allows us to create animation effects on any numeric CSS property. This method changes an element from one state to another with CSS styles. The CSS property value is changed gradually, to create an animated effect.

Syntax is:
 Collapse | Copy Code
(selector).animate({styles},speed,easing,callback)
  • styles: Specifies one or more CSS properties/values to animate.
  • duration: Optional. Specifies the speed of the animation.
  • easing: Optional. Specifies the speed of the element in different points of the animation. Default value is "swing".
  • callback: Optional. A function to be executed after the animation completes.
Simple use of animate function is,
 Collapse | Copy Code
$("btnClick").click(function(){
  $("#dvBox").animate({height:"100px"});
});
Q39. How to disable jQuery animation?
Ans: Using jQuery property "jQuery.fx.off", which when set to true, disables all the jQuery animation. When this is done, all animation methods will immediately set elements to their final state when called, rather than displaying an effect.

Q40. How do you stop the currently-running animation?
Ans: Using jQuery ".stop()" method.

Q41. What is the difference between .empty(), .remove() and .detach() methods in jQuery?
Ans: 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.

Q42. Explain .bind() vs .live() vs .delegate() vs .on()

Or

Q what are the methods of jquery which is attaching the events to selector or elements

Ans: All these 4 jQuery methods are used for attaching events to selectors or elements. But they all are different from each other.

.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. bind() only attach events to the current elements not future element. Above that it also 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. Because of its poor performance on large pages, this method is deprecated as of jQuery 1.7 and you should stop using it. 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 and it also 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.

Q43. What is wrong with this code line "$('#myid.3').text('blah blah!!!');"
Ans: The problem with above statement is that the selectors is having meta characters and to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar").
So the correct syntax is,
 Collapse | Copy Code
$('#myid\\.3').text('blah blah!!!');


Q44. How to create clone of any object using jQuery?
Ans: jQuery provides clone() method which performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.
 Collapse | Copy Code
$(document).ready(function(){
  $('#btnClone').click(function(){
     $('#dvText').clone().appendTo('body');
     return false;
  });
});
Q45. Does events are also copied when you clone any element in jQuery?
Ans: As explained in previous question, using clone() method, we can create clone of any element but the default implementation of the clone()method doesn't copy events unless you tell the clone() method to copy the events. The clone() method takes a parameter, if you pass true then it will copy the events as well.
 Collapse | Copy Code
$(document).ready(function(){
   $("#btnClone").bind('click', function(){
     $('#dvClickme').clone(true).appendTo('body');
  });
​
Q46. What is difference between prop and attr?
Ans: attr(): Get the value of an attribute for the first element in the set of matched elements. Whereas,.prop(): (Introduced in jQuery 1.6) Get the value of a property for the first element in the set of matched elements.

Attributes carry additional information about an HTML element and come in name="value" pairs. Where Property is a representation of an attribute in the HTML DOM tree. once the browser parse your HTML code ,corresponding DOM node will be created which is an object thus having properties.

attr() gives you the value of element as it was defines in the html on page load. It is always recommended to use prop() to get values of elements which is modified via javascript/jquery , as it gives you the original value of an element's current state. Find out more here.

Q47. What is event.PreventDefault?
Ans: The event.preventDefault() method stops the default action of an element from happening. For example, Prevents a link from following the URL.

Q48. What is the difference between event.PreventDefault and event.stopPropagation?
Ans: event.preventDefault(): Stops the default action of an element from happening.
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.

Q49. What is the difference between event.PreventDefault and "return false"?
Ans: e.preventDefault() will prevent the default event from occurring, e.stopPropagation() will prevent the event from bubbling up and return false will do both.

Q50. What is the difference between event.stopPropagation and event.stopImmediatePropagation?
Ans: 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.
 Collapse | Copy Code
$("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 caseevent.stopImmediatePropagation(), the next p click event will not fire.

Q51. How to check if number is numeric while using jQuery 1.7+?
Ans: Using "isNumeric()" function which was introduced with jQuery 1.7.

Q52. How to check data type of any variable in jQuery?
Ans: Using $.type(Object) which returns the built-in JavaScript type for the object.

Q53. How do you attach a event to element which should be executed only once?
Ans: Using 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.
 Collapse | Copy Code
$(document).ready(function() {
    $("#btnDummy").one("click", function() {
        alert("This will be displayed only once.");
    });
});​
Q54. Can you include multiple version of jQuery? If yes, then how they are executed?
Ans: Yes. Multiple versions of jQuery can be included in same page.

Q55. In what situation you would use multiple version of jQuery and how would you include them?
Ans: Well, it is quite possible that the jQuery plugins which are used are dependent on older version but for your own jQuery code, you would like to use newer version. So because of this dependency, multiple version of jQuery may required sometimes on single page.

Below code shows how to include multiple version of jQuery.
 Collapse | Copy Code
<script type='text/javascript' src='js/jquery_1.9.1.min.js'></script>

<script type='text/javascript'>
 var $jq = jQuery.noConflict();
</script>

<script type='text/javascript' src='js/jquery_1.7.2.min.js'></script>
By this way, for your own jQuery code use "$jq", instead of "$" as "$jq" refers to jQuery 1.9.1, where "$" refers to 1.7.2.

Q56. Is it possible to hold or delay document.ready execution for sometime?
Ans: Yes, its possible. With Release of jQuery 1.6, a new method "jQuery.holdReady(hold)" was introduced. This method allows to delay the execution of document.ready()  event. document.ready() event is called as soon as your DOM is ready but sometimes there is a situation when you want to load additional JavaScript or some plugins which you have referenced. 
 Collapse | Copy Code
​
$.holdReady(true);
$.getScript("myplugin.js", function() {
     $.holdReady(false);
});
Q57. What is chaining in jQuery?
Ans: Chaining is one of the most powerful feature of jQuery. In jQuery, Chaining means to connect multiple functions, events on selectors. It makes your code short and easy to manage and it gives better performance. The chain starts from left to right. So left most will be called first and so on.
 Collapse | Copy Code
​$(document).ready(function(){
    $('#dvContent').addClass('dummy');
    $('#dvContent').css('color', 'red');
    $('#dvContent').fadeIn('slow');
});​
The above jQuery code sample can be re-written using chaining. See below.
 Collapse | Copy Code
​$(document).ready(function(){
    $('#dvContent').addClass('dummy')
          .css('color', 'red')
          .fadeIn('slow');    
});​
Not only functions or methods, chaining also works with events in jQuery. Find out more here.

Q58. How does caching helps and how to use caching in jQuery? 
Ans: Caching is an area which can give you awesome performance, if used properly and at the right place. While using jQuery, you should also think about caching. For example, if you are using any element in jQuery more than one time, then you must cache it. See below code.
 Collapse | Copy Code
$("#myID").css("color", "red");
//Doing some other stuff......
$("#myID").text("Error occurred!");
​
Now in above jQuery code, the element with #myID is used twice but without caching. So both the times jQuery had to traverse through DOM and get the element. But if you have saved this in a variable then you just need to reference the variable. So the better way would be,
 Collapse | Copy Code
var $myElement = $("#myID").css("color", "red");
//Doing some other stuff......
$myElement.text("Error occurred!");
​
So now in this case, jQuery won't need to traverse through the whole DOM tree when it is used second time. So in jQuery, Caching is like saving the jQuery selector in a variable. And using the variable reference when required instead of searching through DOM again.

Q59. You get "jquery is not defined" or "$ is not defined" error. What could be the reason?
Ans: There could be many reasons for this.

  • You have forgot to include the reference of jQuery library and trying to access jQuery.
  • You have include the reference of the jQuery file, but it is after your jQuery code.
  • The order of the scripts is not correct. For example, if you are using any jQuery plugin and you have placed the reference of the plugin js before the jQuery library then you will face this error.
Q60. How to write browser specific code using jQuery?
Ans: Using jQuery.browser property, we can write browser specific code. This property contains flags for the user agent, read from navigator.userAgent. This property was removed in jQuery 1.9.

Q61. Can we use jQuery to make ajax request?
Ans: Yes. jQuery can be used for making ajax request.

Q62. What are various methods to make ajax request in jQuery?
Ans: 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.
 Q63. Is there any advantage of using $.ajax() for ajax call against $.get() or $.post()?
Ans: By using jQuery post()/ jQuery get(), you always trust the response from the server and you believe it is going to be successful all the time. Well, it is certainly not a good idea to trust the response. As there can be n number of reason which may lead to failure of response.

Where 
jQuery.ajax() is jQuery's low-level AJAX implementation. $.get and $.post are higher-level abstractions that are often easier to understand and use, but don't offer as much functionality (such as error callbacks).
Q64. What are deferred and promise object in jQuery?
Ans: Deferred and promise are part of jQuery since version 1.5 and they help in handling asynchronous functions like Ajax.

Q65. Can we execute/run multiple Ajax request simultaneously in jQuery? If yes, then how?
Ans: Yes, it is possible to execute multiple Ajax request simultaneously or in parallel. Instead of waiting for first ajax request to complete and then issue the second request is time consuming. The better approach to speed up things would be to execute multiple ajax request simultaneously.

Using jQuery 
.when() method which provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.
Q66. Can you call C# code-behind method using jQuery? If yes,then how?
Ans: Yes. We can call C# code-behind function via $.ajax. But for do that it is compulsory to mark the method as WebMethod.

Q67. Which is the latest version of jQuery library?
Ans: The latest version (when this post is written) of jQuery is 1.10.2 or 2.0.3. jQuery 2.x has the same API as jQuery 1.x, but does not support Internet Explorer 6, 7, or 8.

Q68. Does jQuery 2.0 supports IE?
Ans: No. jQuery 2.0 has no support for IE 6, IE 7 and IE 8.

Q69. What are source maps in jQuery?
Ans: In case of jQuery, Source Map is nothing but mapping of minified version of jQuery against the un-minified version. Source map allows to debug minified version of jQuery library. Source map feature was release with jQuery 1.9
Q70. How to use migrate jQuery plugin?
Ans: with release of 1.9 version of jQuery, many deprecated methods were discarded and they are no longer available. But there are many sites in production which are still using these deprecated features and it's not possible to replace them overnight. So jQuery team provided with jQuery Migrate plugin that makes code written prior to 1.9 work with it.

So to use old/deprecated features, all you need to do is to provide reference of jQuery Migrate Plugin
Q71. Is it possible to get value of multiple CSS properties in single statement?
Ans: Well, before jQuery 1.9 release it was not possible but one of the new feature of jQuery 1.9 was .css() multi-property getter.
 Collapse | Copy Code
var propCollection = $("#dvBox").css([ "width", "height", "backgroundColor" ]);
In this case, the propCollection will be an array and it will look something like this.
 Collapse | Copy Code
{
  width: "100px",
  height: "200px",
  backgroundColor: "#FF00FF"
}
Q72. How do you stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements?
Ans: It can be done via calling .stop([clearQueue ] [, jumpToEnd ]) method and by passing both the parameters as true.

Q73. What is finish method in jQuery?
Ans: The .finish() method stops all queued animations and places the element(s) in their final state. This method was introduced in jQuery 1.9.

Q74. What is the difference between calling stop(true,true) and finish method?
Ans: The .finish() method is similar to .stop(true, true) in that it clears the queue and the current animation jumps to its end value. It differs, however, in that .finish() also causes the CSS property of all queued animations to jump to their end values, as well.

Q75. Consider a scenario where things can be done easily with javascript, would you still prefer jQuery?
Ans: No. If things can be done easily via CSS or JavaScript then You should not think about jQuery. Remember, jQuery library always comes with xx kilobyte size and there is no point of wasting bandwidth.

Q76. Can we use protocol less URL while referencing jQuery from CDNs?
Ans: Yes. Below code is completely valid.
 Collapse | Copy Code
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Q77. What is the advantage of using protocol less URL while referencing jQuery from CDNs?
Ans: It is quite useful when you are moving from HTTP to HTTPS url. You need to make sure that correct protocol is used for referencing jQuery library as pages served via SSL should contain no references to content served through unencrypted connections.

"protocol-less" URL is the best way to reference third party content that’s available via both HTTP and HTTPS. When a URL’s protocol is omitted, the browser uses the underlying document’s protocol instead. Find out more 
here.

Q78. What is jQuery plugin and what is the advantage of using plugin?
Ans: A plug-in is piece of code written in a standard JavaScript file. These files provide useful jQuery methods which can be used along with jQuery library methods. jQuery plugins are quite useful as its piece of code which is already written by someone and re-usable, which saves your development time.

Q79. What is jQuery UI?
Ans: jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library that can be used to build interactive web applications.

Q80. What is the difference between jQuery and jQuery UI?
Ans: jQuery is the core library. jQueryUI is built on top of it. If you use jQueryUI, you must also include jQuery.

Note: If you have any questions to add to this list then please put it comments. We will be glad to add them in this list. We will be keep on updating this list with new questions and share the updates on our 
Facebook or Twitter channel. If you are not following us then request you to please follow and stay updated.
jQuery interview questions and answers
1.What is jQuery Selectors? Give some examples.
2. How can we give face effect in jQuery?
3. Explain the animate function.
4. What is .siblings() method in jQuery?
5. Explain width() vs css(‘width’).
6. What is the use of jQuery.data()?
7. Explain bind() vs live() vs delegate() methods.
8. Explain the each() function.
9. Explain slideToggle() effect.
10. What is difference between $(this) and ‘this’ in jQuery?
11. What is the use of param() method.
12. What is jQuery.holdReady() function?
13. Explain .empty() vs .remove() vs .detach().
14. How to read, write and delete cookies in jQuery?
15. Is window.onload is different from document.ready()?
16. What is Chaining in jQuery?
17. What is difference between sorting string array and sorting numerical array in jQuery?
18. What is difference between prop and attr?
19. How to always reference latest version of jQuery?
20. What is resize() function in jQuery?

23.Explain the features of jQuery.
Latest answer: Features of jQuery are : Effects and animations, Ajax, Extensibility.............
26.Explain how jQuery Works.
Latest answer: <html>
     <head>
     <script type="text/javascript" src="jquery.js"></script>
     <script type="text/javascript">................
27.When can you use jQuery?
 JQuery can be used to
Apply CSS , call functions on events, Traverse the documents.
1) What is jQuery Selectors? Give some examples.
jQuery Selectors are used to select one or a group of HTML elements from your web page. jQuery support all the CSS selectors as well as many additional custom selectors. jQuery selectors always start with dollar sign and parentheses: $() There are three building blocks to select the elements in a web document.
1) Select elements by tag name
Example: $(div) It will select all the div elements in the document.
2) Select elements by ID Example: $(#xyzid”) It will select single element that has an ID of xyzid
3) Select elements by class Example: $(“.xyzclass”) It will select all the elements having class xyzclass


2) How can we give face effect in jQuery?
In jQuery we have three methods to give the fade effect to elements: fadeIn, fadeOut and fadeTo
This methods change the opacity of element with animation.
Syntax:
$(selector).fadeIn(speed,callback)
$(selector).fadeOut(speed,callback)
$(selector).fadeTo(speed,opacity,callback)
“speed” can be one of following values : “slow”, “fast”, “normal” or milliseconds
“opacity” specify the value that allows the fading to given opacity.
“callback” is the function which we want to run once the fading effect is complete.
For example
$("clickme").click(function(){
$("mydiv").fadeTo("slow",0.50);
});
$("clickme").click(function(){
$("mydiv").fadeOut(3000);
});.
3) Explain the animate function.
-The animate function is used to apply the custom animation effect to elements.
-Syntax:
$(selector).animate({params}, [duration], [easing], [callback])
“param” defines the CSS properties on which you want to apply the animation.
“duration” specify how long the animation will run. It can be one of following values : “slow”, “fast”, “normal” or milliseconds
“easing” is the string which specify the function for the transition.
“callback” is the function which we want to run once the animation effect is complete.
For example
<div id="clickToAnimate">
Click Me
</div>
<div id="mydiv" style=”width:200px; height:300px; position: relative; right: 20px;">
</div>

Following is the jQuery to animate opacity, left offset, and height of the mydiv element

$('# clickToAnimate’).click(function() {
$('#book').animate({
opacity: 0.30,
left: '+=20',
height: 'toggle'
}, 3000, function() {
// run after the animation complete.
});
});

4) What is .siblings() method in jQuery?
When we want to fetch siblings of every elements in the set of matched elements then we can use siblings() method.
We filter the elements fetched by an optional selector.
Syntax : .siblings( [selector])
“selector” is the selector expression which specify the matched elements.
For example

<ul>
<li> item 1 </li>
<li id=”second_item”> item 2 </li>
<li class=”myitem”> item 3 </li>
<li class=”myitem”> item 4 </li>
</ul>

Now we want to find the siblings of the element of id “second_item” and change the text color to Blue :

$(‘li.second_item’).siblings().css(‘color’,’blue’);

If we want specific sibling elements for example the elements having class “myitem” then we can pass a optional selector:
$(‘li.second_item’).siblings(‘.myitem’).css(‘color’,’blue’);

5) Explain width() vs css(‘width’).

In jQuery, there are two way to change the width of an element.
One way is using .css(‘width’) and other way is using .width().
For example

$(‘#mydiv’).css(‘width’,’300px’);
$(‘#mydiv’).width(100);

The difference in .css(‘width’) and .width() is the data type of value we specify or return from the both functions.
In .css(‘width’) we have to add “px” in the width value while in .width() we don’t have to add.
When you want to get the width of “mydiv” element then .css(‘width’) will return ‘300px’ while .width() will return only integer value 300.
6) What is the use of jQuery.data()?

jQuery.data() is used to set/return arbitrary data to/from an element.
Syntax: jQuery.data(element, key, value)
“element” is the DOM element to which the data is associated.
“key” is an arbitrary name of the piece of data.
“value” is value of the specified key.
Suppose we want to set the data for a span element:
jQuery.data(span, “item”, { val1: 10, val2: "myitem" });

If we want to retrieve the data related to div element and set it to label’s data:

$("label:val1").text(jQuery.data(div, "item").val1);
$("label:val2").text(jQuery.data(div, "item").val2);

7) Explain bind() vs live() vs delegate() methods.

-The bind() method will not attach events to those elements which are added after DOM is loaded while live() and delegate() methods attach events to the future elements also.
-The difference between live() and delegate() methods is live() function will not work in chaining. It will work only on an selector or an element while delegate() method can work in chaining.

For example
$(document).ready(function(){
$("#myTable").find("tr").live("click",function(){
alert($(this).text());
});
});

Above code will not work using live() method. But using delegate() method we can accomplish this.

$(document).ready(function(){
$("#dvContainer")children("table").delegate("tr","click",function(){
alert($(this).text());
});
});

8) Explain the each() function.

-The each() function specify the function to be called for every matched element.

Syntax:

$(selector).each(function (index, element))

“index” is the index position of the selector.
“selector” specifies the current selector where we can use “this” selector also.
In the case when we need to stop the each loop early then we can use “return false;”
For example

$("#clickme").click(function(){
$("li").each(function(){
document.write($(this).text())
});
});
This will write the text for each “li” element.

9) Explain slideToggle() effect.

-slideToggle() effect is used to give animated sliding effect to an element.

Syntax:

slideToggle([ duration] [, easing] [, callback])

“duration” is the number specifying how long the animation will run.
“easing” is the string which specify the function for the transition.
“callback” is the function which we want to run once the animation is complete.
If the element is visible then this effect will slide the element up side and make it completely hidden. If the element is hidden then slideToggle() effect will slide it down side and make it visible.
We can specify the toggle speed with this effect.
For example

$("#clickme").click(function(){
$("#mydiv").slideToggle(“slow”, function(){
//run after the animation is complete.
});
});

10) What is difference between $(this) and ‘this’ in jQuery?

Refer the following example

$(document).ready(function(){
$(‘#clickme’).click(function(){
alert($(this).text());
alert(this.innerText);
});
});

-this and $(this) references the same element but the difference is that “this” is used in traditional way but when “this” is used with $() then it becomes a jQuery object on which we can use the functions of jQuery.
-In the example given, when only “this” keyword is used then we can use the jQuery text() function to get the text of the element, because it is not jQuery object. Once the “this” keyword is wrapped in $() then we can use the jQuery function text() to get the text of the element.

11) What is the use of param() method.

The param() method is used to represent an array or an object in serialize manner.
While making an ajax request we can use these serialize values in the query strings of URL.
Syntax: $.param(object | array, boolValue)
“object | array” specifies an array or an object to be serialized.
“boolValue” specifies whether to use the traditional style of param serialization or not.
For example:

personObj=new Object();
empObject.name="Arpit";
empObject.age="24";
empObject.dept=”IT”;
$("#clickme").click(function(){
$("span").text($.param(empObject));
});
It will set the text of span to “name=Arpit&age=24&dep=IT”

12) What is jQuery.holdReady() function?

-By using jQuery.holdReady() function we can hold or release the execution of jQuery’s ready event.
-This method should be call before we run ready event.
-To delay the ready event, we have to call

jQuery.holdReady(true);

-When we want to release the ready event then we have to call
jQuery.holdReady(false);
-This function is helpful when we want to load any jQuery plugins before the execution of ready event.

For example

$.holdReady(true);
$.getScript("xyzplugin.js", function() {
$.holdReady(false);
});

13) Explain .empty() vs .remove() vs .detach().

-.empty() method is used to remove all the child elements from matched elements.
-.remove() method is used to remove all the matched element. This method will remove all the jQuery data associated with the matched element.
-.detach() 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.

Syntax:

$(selector).empty();
$(selector).remove();
$(selector).detach();

14) How to read, write and delete cookies in jQuery?

-To deal with cookies in jQuery we have to use the Dough cookie plugin.
-Dough is easy to use and having powerful features.
-Create cookie

$.dough("cookie_name", "cookie_value");

Read Cookie
$.dough("cookie_name");
Delete cookie
$.dough("cookie_name", "remove");

15) Is window.onload is different from document.ready()?

- The window.onload() is Java script function and document.ready() is jQuery event which are called when page is loaded.
- The difference is that document.ready() is called after the DOM is loaded without waiting for all the contents to get loaded. While window.onload() function waits until the contents of page is loaded.
- Suppose there is very large image on a page, at that time window.onload() will wait until that image is loaded totally.
- So while using the window.onlaod() function the execution will be slow, but the document.ready() will not wait until the image is loaded.

16) What is Chaining in jQuery?

- Chaining is very powerful feature of jQuery.
- Chaining means specifying multiple function and/or selectors to an element.
- Examine the below example

$(document).ready(function(){
$('#mydiv').css('color', 'blue');
$('#mydiv').addClass('myclass');
$('#mydiv').fadeIn('fast');
}

By using chaining we can write above code as follows

$(document).ready(function(){
$('#mydiv').css('color', 'blue').addClass('myclass').fadeIn('fast');
});

-Advantage of chaining is that it makes your code simple and simple to manage.
-The execution becomes faster because the code search for the element only once.

17) What is difference between sorting string array and sorting numerical array in jQuery?

The sort method is used to sort any array elements. It sorts the string elements alphabetically.

For example

$(document).ready(function(){
var mylist = [ “Apple”,”Orange”,”Banana”];
mylist = mylist.sort();
$(“#mydiv”).html(list.join(“”));
});

It will give following output
Apple
Banana
Orange

Now we declare a numerical array and use sort() method to sort its elements.

$(document).ready(function(){
var mylist = [ “20”,”3””100”,”50”];
mylist = mylist.sort();
$(“#mydiv”).html(list.join(“”));
});

It will give following output
100
20
3
50

18) What is difference between prop and attr?

In jQuery both prop() and attr() function is used to set/get the value of specified property of an element.
The difference in both the function is that attr() returns the default value of the property while the prop() returns the current value of the property.
For example

<input value="My Value" type="text"/>

$('input').prop('value', 'Changed Value');

-.attr('value') will return 'My Value'
-.prop('value') will return 'Changed Value'

19) How to always reference latest version of jQuery?

When you reference the jQuery on your web page, you have to specify the version number also.

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

Above code will always load the 1.5.1 version of jQuery. If you reference the latest jQuery then you don’t need to change the code every time the new version of jQuery is released.

To achieve this you have to use following code
<script type=”text/javascript”
src=”http://code.jquery.com/jquery-latest.min.js”>
</script>

This code will always reference the latest version of jQuery in your page.

20) What is resize() function in jQuery?

The resize() function is called whenever the browser size is changed. This event can be only used with $(window).

Syntax:

.resize([event_data], handler(event_object))

-The “event_data” is the data to be sent to the handler.
-The “handler(event_object)” is a function to be called each time when the window is resized.

For example

$(window).resize(function() {
$('#message).text('window is resized to ' + $(window).width() + ‘x’ + $(window).height());
});

jQuery interview questions and answers are below



Questions : 2
How you will use Jquery means requirement needed for using jquery
Answers : 2
Nothing more need to do just olny download jquery library(.js file) from any of the jquery siteDownload jquery and just linked with your html pages like all other javascript file
like below : 
< script src="jquery.js" language="javascript" type="text/javascript">

Questions : 4
How do you select an item using css class or ID and get the value by use of jquery
Answers : 4
If an element of html like < div> , < p> or any tag have ID MyId and class used MyClass then we select the element by below jquery code

$('#MyId') for ID and for classs $('.MyClass') and for value

var myValue = $('#MyId').val(); // get the value in var Myvalue by id 
Or for set the value in selected item 

$('#MyId').val("print me"); // set the value of a form input


Questions : 5
How to get the server response from an AJAX request using Jquery? 
Answers :
When invoking functions that have asynchronous behavior We must provide a callback function to capture the desired result. This is especially important with AJAX in the browser because when a remote request is made, it is indeterminate when the response will be received.
Below an example of making an AJAX call and alerting the response (or error):
 $.ajax({
     url: 'pcdsEmpRecords.php',
     success: function(response) {
        alert(response);
     },
     error: function(xhr) {
        alert('Error!  Status = ' + xhr.status);
     }
 });


Questions : 6
How do you update ajax response with id " resilts" 
Answers : 6
By using below code we can update div content where id 'results' with ajax response
 function updateStatus() {
     $.ajax({
            url: 'pcdsEmpRecords.php',
            success: function(response) {
             // update div id Results 
             $('#results').html(response);
         }
     });
 }


Questions : 7
How do You disable or enable a form element? 
Answers : 7
There are two ways to disable or enable form elements.
Set the 'disabled' attribute to true or false:
 // Disable #pcds
 $('#pcds').attr('disabled', true);
 // Enable #pcds
 $('#pcds').attr('disabled', false);
Add or remove the 'disabled' attribute:
 // Disable #pcds
 $("#pcds").attr('disabled', 'disabled');
 // Enable #x
 $("#pcds").removeAttr('disabled');


Questions : 8
How do you check or uncheck a checkbox input or radio button? 
Answers : 8
There are two ways to check or uncheck a checkbox or radio button.
Set the 'checked' attribute to true or false.
 // Check #pcds
 $('#pcds').attr('checked', true);
 // Uncheck #pcds
 $('#pcds').attr('checked', false);
Add or remove the 'checked' attribute:
 // Check #pcds
 $("#pcds").attr('checked', 'checked');
 // Uncheck #pcds
 $("#pcds").removeAttr('checked');


Questions : 9
How do you get the text value of a selected option? 
Answers : 9
Select elements typically have two values that you want to access. First there's the value to be sent to the server, which is easy:
 $("#pcdsselect").val();
 // => 1
The second is the text value of the select. For example, using the following select box:
 <select id="pcdsselect">
 
   <option value="1">Mr</option>
   <option value="2">Mrs</option>
   <option value="3">Ms</option>
   <option value="4">Dr</option>
 
   <option value="5">Prof</option>
 </select>
If you wanted to get the string "Mr" if the first option was selected (instead of just "1"), you would do that in the following way:
 $("#mpcdsselect option:selected").text();
 // => "Mr"

Whether you’re looking to prepare for an interview for JavaScript role, you’re an interviewer looking for inspiration or you just want to evaluate your JavaScript knowledge here are 10 advanced topics that a software engineer working with JavaScript should be able to answer. Bear in mind that answers here are kept minimal, there are lots of caveats not mentioned.
When would you use var in your declaration and when you wouldn’t?
Always use var. Not using var for variable declaration will traverse scopes all the way up till the global scope. If variable with that name is not found it will declare it in the global scope. Therefore not using var implicitly declares variable in the global scope (which, let me remind you, is a bad practice).
(function() {
   baz = 5;
   var bar = 10;
})();
 
console.log(baz); // outputs 5
//console.log(bar); // error: bar is not defined
A common mistake is to not use var in loops which might, in some cases, bear unexpected results or pollute the global scope:
(function() {
    var baz = "Hello World";
    for(var bar=1; bar
What does the attribute defer/async do when added to the script tag?
The defer attribute will cause browser to execute script after the document has been parsed. This attribute was first implemented in Internet Explorer 4, then added to HTML 4 and more recently HTML 5 spec. You might not have heard of it as it has not been supported till version 3.5 (Gecko 1.9.2). Async is another attribute that can affect how a script is loaded and executed, here is a quote from HTML 5 spec on how this is expected to work:
There are three possible modes that can be selected using these attributes. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.
Note: A somewhat (but not exactly) similar defer behavior can be achieved by placing your script tags at the end of the body tag and that’s what is considered to be modern ‘best practice’
What is the difference between == and ===? Which one would you use?
The equality (==) operator will compare for equality after doing necessary type casting, the identity operator (===) doesn’t do any conversions. A good practice suggested by Douglas Crockford is to always use strict equality,  couple of examples from Douglas’ book JavaScript: The Good Parts
'' == '0'          // false
0 == ''            // true
0 == '0'           // true
 
false == 'false'   // false
false == '0'       // true
 
false == undefined // false
false == null      // false
null == undefined  // true
How would you check if a variable is null/undefined?
//check if bar is null
bar === null
//check if bar is undefined
typeof bar === "undefined"
How do you check if a variable is an object
You can use 
typeof to determine if variable is an object, however bear in mind that null is actually an object! However null object is ‘falsy’ thus the following will work:
if(bar && typeof bar === "object") {
    console.log('bar is object and is not null');
}
Discuss  scoping in JavaScript.
JavaScript has lexical scoping based on functions but not blocks. Therefore:
//global scope
(function() {
    //anonymous function scope
    var foo = 1;
    function bar() {
        //bar function scope
        var foo = 2;
    }
    bar();
    console.log(foo); //outputs 1
    if(true) {
        var foo = 3; //redeclares foo
    }
    console.log(foo); //outputs 3
})();
Try it: http://jsfiddle.net/tnajdek/8y3XC/. Note: from within function scope everything in above scope(s) is available (see closures below)
Explain hoisting in JavaScript.
As some might not be familiar with the term ‘hoisting’ yet have the relevant experience this question could be asked indirectly
In JavaScript function declarations ( function foo() {} ) and variable declarations ( var bar  ) are ‘hoisted’ i.e. are silently moved to the very top of the scope. Consider the following code:
(function() {
    console.log(bar); //returns 'undefined'
    //console.log(baz) // error: baz is not defined
    foo(); // outputs 'aloha' to the console
 
    //function declaration AND its body is hoisted
    function foo() {
        console.log('aloha');
    }
    //variable declaration is hoisted but value assignment stays here
    var bar = 1;
    baz = 2; //defines baz in global scope
})();
What are closures?
(function() {
    function foo(x) {
        var baz = 3;
        return function (y) {
        console.log(x + y + (++baz));
        }
    }
var moo = foo(2); // moo is now a closure.
moo(1); // 7
moo(1); // 8!
})();
The inner function inside foo will close-over the variables of foo before leaving creating a closure.
Explain prototypal/differential inheritance
Conceptually this is very simple: A new object can inherit properties of an old object.
(function() {
    var genericObject = {
        bar : "Hello World",
        get_bar : function() {
            return this.bar;
        }
    };
    var customObject = Object.create(genericObject);
    customObject.bar = "Aloha folks!";
    console.log(customObject.get_bar()); //outputs: "Aloha folks"
    delete customObject.bar;
    console.log(customObject.get_bar()); //fallbacks to the prototype's value, outputs: "Hello World"
})();
While JavaScript has always been a prototype-oriented language, tools to work with prototypes were somewhat missing. Object.create used in the code snipped above has been added in ECMAScript 5 and has not been supported prior to Firefox 4, Chrome 5, IE 9
What is Strict Mode in JavaScript
Strict Mode has been introduced as part of ECMAScript 5 and introduces new, restricted variant of JavaScript which has following aims:
·         Throws errors for actions that are rather silly but previously didn’t throw an error
·         Throws errors for potentially unsafe actions
·         Disables functions that are poorly thought out
·         Potentially code in strict mode could run faster by eliminating mistakes that would make it difficult for JavaScript engines to perform optimizations
Strict mode can be enabled for the entire source file or on per function basis by adding a string literal “use strict” on top of the file/function i.e.
function foo(){
  "use strict";
  // ... your code ...
}

JavaScript Interview Questions for both Experienced and Fresher


1).What is JavaScript?
Ans:-JavaScript is a scripting language most often used for client-side web development.


2).Difference between JavaScript and Jscript?
Ans:-Both JavaScript and Jscript are almost similar. Java script was developed by Netscape. Microsoft reverse engineered Javascript and called it JScript


3).How do we add JavaScript onto a web page?
Ans:-
There are serveral way for adding javascript on a web page but there are two way with is commonly userd by developers
If your script code is very short and only for single page then following ways is best
a)You can place <script type="text/javascript"> tag inside the <head> element. 
Code:
<head>
<title>Page Title</title>
<script language="JavaScript" type="text/javascript">
   var name = "Vikas Ahlawta"
   alert(name);
</script>
</head>
b).If your script code is very large then you can make a javascript file and add its path in the following way..
Code:
<head>
<title>Page Title</title>
<script type="text/javascript" src="myjavascript.js"></script>
</head>


4).Is JavaScript case sensitive?
Ans:-Yes!
A function getElementById is not the same as getElementbyID


5).What are the types used in JavaScript? 
Ans:-String, Number, Boolean, Function, Object, Null, Undefined.


6).What are the boolean operators sported by JavaScript?
And Operator: &&
Or Operator: ||
Not Operator: !


7).What is the difference between “==” and “===”?
Ans:-
“==” checks equality only, 
“===” checks for equality as well as the type.


8).How to access the value of a textbox using JavaScript?
Ans:-
ex:-
Code:
<!DOCTYPE html>
<html>
<body>
Full name: <input type="text" id="txtFullName" name="FirstName" value="Vikas Ahlawat">
</body>
</html>

There are following way to access the value of the above textbox
var name = document.getElementById('txtFullName').value;
alert(name);
or 
we can use the old way
document.forms[0].mybutton.
var name = document.forms[0].FirstName.value;
alert(name);
Note:- this uses the "name" attribute of the element to locate it.


9).What are the way of make comment in Javascript?
Ans:-
// is used for line comments
ex:- var x=10; //comment text

/*
*/ is used for block comments
ex:-
var x= 10; /* this is
block comment example.*/


10).How you will get the CheckBox status whether it is checked or not?
Ans:-
var status = document.getElementById('checkbox1').checked; 
alert(status); 
it will return true or false


11).How to create arrays in JavaScript? 
Ans:-
There are Two way dor create array in Javascript like other languages..
a) first way to create array
Declare Array:-
Code:
var names = new Array(); 
Add Elements in Array:-
names[0] = "Vikas";
names[1] = "Ashish";
names[2] = "Nikhil";

b) this is second way
var names = new Array("Vikas", "Ashish", "Nikhil");


12).If an array with name as "names" contain three elements then how you will print the third element of this array?
Ans:- Print third array element document.write(names[2]); 
Note:- array index start with 0


13).How do you submit a form using Javascript? 
Ans:-Use document.forms[0].submit();


14).What does isNaN function do? 
Ans:-
It Return true if the argument is not a number.
ex:-
Code:
document.write(isNaN("Hello")+ "<br>");
document.write(isNaN("2013/06/23")+ "<br>");
document.write(isNaN(123)+ "<br>");

output will be:-
true
true
false


15).What is the use of Math Object in Javascript?
Ans:-
The math object provides you properties and methods for mathematical constants and functions.
ex:-
Code:
var x = Math.PI; // Returns PI
var y = Math.sqrt(16); // Returns the square root of 16
var z = Math.sin(90);    Returns the sine of 90

16). What do you understand by this keyword in javascript? 
Ans:-In JavaScript the this is a context-pointer and not an object pointer. It gives you the top-most context that is placed on the stack. The following gives two different results (in the browser, where by-default the window object is the 0-level context):

Code:
var obj = { outerWidth : 20 };

function say() {
    alert(this.outerWidth);
}
say();//will alert window.outerWidth
say.apply(obj);//will alert obj.outerWidth


17).What does "1"+2+4 evaluate to? 
Ans:-Since 1 is a string, everything is a string, so the result is 124. 


18).What does 3+4+"7" evaluate to?
Ans:-Since 3 and 4 are integers, this is number arithmetic, since 7 is a string, it’s concatenation, so 77 is the result.


19).How do you change the style/class on any element using javascript?
Ans:-
Code:
document.getElementById(“myText”).style.fontSize = “10";
-or-
document.getElementById(“myText”).className = “anyclass”;


20).Does javascript support foreach loop?
Ans:- Yes, See example here 
http://jsfiddle.net/gpDWk/ 


21).What looping structures are there in JavaScript? 
Ans:-for, while, do-while loops


22).what is an object in JavaScript, give an example?
Ans:-
An object is just a container for a collection of named values

// Create the man object
Code:
var man = new Object();
man.name = 'Vikas Ahlawat';
man.living = true;
man.age = 27;


23).How you will add function as a property in a JavaScript object? Give example.
Ans:-
Code:
var man = new Object();
man.name = 'Vikas Ahlawat';
man.living = true;
man.age = 27;

man.getName = function() { return man.name;}
console.log(man.getName()); // Logs 'Vikas Ahlawat'.


24).What is the similarity between 1st and 2nd statement?
1st:- var myString = new String('male'); // An object.
2nd:- var myStringLiteral = 'male'; // Primitive string value, not an object.
Ans:- Both will call String() constructor function
you can confirm it by run the following statement
console.log(myString.constructor, myStringLiteral.constructor);


25).What will be the output of the following statements?
Code:
var myString = 'Vikas' // Create a primitive string object.
var myStringCopy = myString; // Copy its value into a new variable.
var myString = null; // Manipulate the value
console.log(myString, myStringCopy);
Ans:- // Logs 'null Vikas'


26).Consider the following statements and tell what would be the output of the logs statements?
var price1 = 10;
var price2 = 10;
var price3 = new Number('10'); // A complex numeric object because new was used.
console.log(price1 === price2); 
console.log(price1 === price3);
Ans:-
console.log(price1 === price2); // Logs true.
console.log(price1 === price3); /* Logs false because price3 contains a complex number object and price 1
is a primitive value. */


27).What would be the output of the following statements?
var object1 = { same: 'same' };
var object2 = { same: 'same' };
console.log(object1 === object2);
Ans:- // Logs false, JavaScipt does not care that they are identical and of the same object type.
When comparing complex objects, they are equal only when they reference the same
object (i.e. have the same address). Two variables containing identical objects are not
equal to each other since they do not actually point at the same object.


28).What would be the output of the following statements?
Code:
var object1 = { same: 'same' };
var object2 = object1;
console.log(object1 === object2);
Ans:- // Logs true


29).What is this?
var myArray = [[[]]];
Ans:- Three dimantional array


30).Name any two JavaScript functions which are used for convert nonnumeric values into numbers?
Ans:-
Number()
parseInt()
parseFloat()
Code:
var n1 = Number(“Hello world!”); //NaN
var n2 = Number(“”);             //0
var n3 = Number(“000010”);       //10
var n4 = Number(true);           //1
var n5 = Number(NaN);            //NaN

 Advanced Javascript Interview Questions and Answers pdf for Web/UI Developers
Hey here I come with second set of JavaScript Interview questions and answers. I found the most of the experienced JavaScript/UI developers are struggling to find the Advanced/Complex interview questions with his answers respectively. So if you are searching for same then this set of Interview questions would be going to helpful for you as preparation of selection in top MNC(s).

If you want to previous set questions(1-30) then click the following link as given below : 
Set-1 containing(1-30) interview questions

Set-2

31). What is the use of IsNan() function in JavaScript?
Ans:-isNaN() function accepts a single argument, which can be of any data type, to determine if the value is “not a number.”.
For more:-
Code:
alert(isNaN(“red”)); //true - cannot be converted to a number
alert(isNaN(true)); //false - can be converted to number 1
alert(isNaN(NaN)); //true
alert(isNaN(5)); //false - 5 is a number
alert(isNaN(“5”)); //false - can be converted to number 5


32). Can you describe "===" operator?
Ans:-
The identically equal operator is represented by three equal signs "===" and returns true only if the operands are equal without
conversion, as in this example
Code:
var result1 = (“55” == 55); //true - equal because of conversion
var result2 = (“55” === 55); //false - not equal because different data
types


33). DOM method "document.getElementById()" didn’t exist in Internet Explorer
prior to version 5. What is the way to detect that "document.getElementById()" is supported by the browser or not?
 
Ans:-
if (document.getElementById){
return document.getElementById("txtBox1");
}
else {
throw new Error(“getElementById function not supported by browser”);
}


34). How do you check if a variable is an array in JavaScript?
Ans:- We can use "instanceof Array"
Example:-
Code:
if (v1 instanceof Array) {
alert('v1 is Array!');
} else {
alert('v1 is not an array');
}

35). What is the difference between following two 
var myfunc = function() {}
function myfunc() {}

Ans:-
var myfunc = function() {} defines a variable that references an anonymous function.
function myfunc() {} defines a named function "myfunc".


36). When we try to convert a sting into Boolean then in JavaScritp it will show error/true/false?
var message = "Hello!!";
var messageAsBoolean = Boolean(message);
alert(messageAsBoolean);
Ans:-Alert box will show "true"
Other Conversion 
<!DOCTYPE html>
<html>
<head>
<script>
var SimpleString = "Hello!!";
var EmptyString = "";
var ZeroNumber = 0;
var NoneZeroNumber = 7;
var NanString = NaN;
var Obj = new Object();
var Undifined;

//Convert into Boolean
var SimpleStringAsBoolean = Boolean(SimpleString); //true
var EmptyStringAsBoolean = Boolean(EmptyString); //fasle
var ZeroNumberAsBoolean = Boolean(ZeroNumber); //false
var NoneZeroNumberAsBoolean = Boolean(NoneZeroNumber); //true
var NanStringAsBoolean = Boolean(NanString); //false
var UndifinedAsBoolean = Boolean(Undifined); //false

//See result
alert(SimpleStringAsBoolean); //Will Show "true"
alert(EmptyStringAsBoolean); //Will Show "false"
alert(ZeroNumberAsBoolean); //Will Show "false"
alert(NoneZeroNumberAsBoolean); //Will Show "true"
alert(NanStringAsBoolean); //Will Show "false"
alert(UndifinedAsBoolean); //Will Show "false"
</script>
</head>
<body>


37). What will be the output of below statement?
alert(NaN == NaN);
Ans:- it will show false
because NaN is not equal to any value, including NaN.


38). What is the difference between undefined value and null value?
Ans:-
Undefined value: If a value that is not defined and has no keyword then it is known as undefined. For example in the declaration, int num; the num has undefined value.
Null value: If a value that is explicitly specified by the keyword ‘null’ then it is known as null value. For example in the declaration, String str=null; the str has a null value. 


39). What would be the difference if we declare two variables inside a JavaScript, one with 'var' keyword and another without 'var' keyword?
Ans:- The variable with var keyword inside a function is treated as Local variable.
and the variable without var keyword inside a function is treated a global variable.


40). Have a look on the following script and tell me which the global/local variables here are.
<script>
var n1= 10;
function my_function()
 
{
var n2 = 0;
 
n3 = 0;
 
}
</script>


Ans:-
<script>
var n1= 10; // Global
function my_function() 
{
var n2 = 0; // is a local
n3 = 0; // is a global
}
</script>

JavaScript Interview Questions: Object-Oriented JavaScript

Object Properties and Methods

In JavaScript, Objects have two things: properties and methods. Methods are simply properties that have a function assigned to them.
Q: What do you call an object’s property when it has been assigned to a function
A: A “method”

Q: True of False: A function can have its own properties and methods.
A: True
Explanation:
Functions inherit from Object. You can add properties and methods to a function at any time. Run the following code in your JavaScript console and you will see this behavior:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//create a function
function foo(){};

//assign a property
foo.color = 'red';

//assign a method
foo.sayHello = function(){
    alert("hello!");
};

//inspect the object
console.dir(foo); //inspect the properties and methods of off

//execute the method
foo.sayHello();// "hello!"

//overwrite a method
foo.sayHello = function(){
    alert("this is a different message");
};

//execute the method
foo.sayHello();// "his is a different message"

Object Syntax

There are different ways to access the properties of an object: bracket notation and dot notation. Care must be taken when deciding which syntax to implement as their behavior differs.
Q: What is the difference between using dot notation and bracket notation when accessing an object’s property?
A: If using dot notation, the property must be a string and refer to a property that exists. When using bracket notation, any valid JavaScript expression that produces a value can be used inside the brackets, such as a variable or an an array element.
Hint:
These are all valid lines of code:
?
1
2
3
4
5
foo = bar.name;
foo = bar["name"];
foo = bar[5 + 5];
foo = bar[ baz() ];
foo = bar[ baz[i] ];

Q: What is important to remember about the last property’s value in a JavaScript object literal?
A : The last property’s value should not be followed by a comma.
Hint: Most browsers will let you get away with it if you forget, but Microsoft Internet Explorer will complain about the extra comma.

Q: Given the following code, what is very likely the reason that the programmer made the first letter of “Foo” a capital letter?
?
1
2
3
var Foo = function(){
this.foo = "bar";
}
A: Foo is meant to be used as a constructor function

Q: Given the following code, how would you instantiate the function “Foo” and assign it to the variable “bar”?
?
1
var Foo = function(){}
A:
?
1
var bar = new Foo();
Here is a jsFiddle.net example: http://jsfiddle.net/vs2Fg/

Creating Objects

There is more than one way to create an object in JavaScript. Which method you chose depends on the type of Object you need to create. For example, there is a difference between an Object Literal and and instance object in JavaScript. Also, while arrays are instances of the Array() constructor, they are still considered object.
Q:What are two ways in which the variable “foo” can be assigned to an empty object?
A:
1.        var foo = new Object();
2.        var foo = {};
Explanation:
When creating a new empty object, you can instantiate the Object() constructor, or you can simply create an empty object literal. In either case, you can then add properties to the new object.
Here is a jsFiddle.net example: 
http://jsfiddle.net/W6X2T/

Q: True or False: When you create an object literal, you must first instantiate the Object() constructor
A: False
Explanation:
In order to create an Object Literal, you assign a variable to an object. The syntax is as simple as var foo = {}. A constructor function is used when creating an instance object, which is a different process.

Q: True of False: You can only instantiate a JavaScript constructor function once.
A: False
Explanation: You can make as many instances as you want.

Q:When using the addEventListener() method to create a click-handler for a DOM element, what is the value of “this” inside of the callback you specify?.
A:The DOM element that was clicked.
Helpful Links:

Different Types of Objects

There is more than one type of object in JavaScript. Some examples are: Functions, Arrays, DOM objects and Date objects. Even NULL is technically an object, although it cannot be mutated.
Q: True or False: A JavaScript array is not an object
A: False
Explanation: JavaScript arrays are objects. They inherit from the JavaScript Object, and have methods and properties that are specific to arrays such as “length” and “sort”
Here is a jsFiddle.net example: http://jsfiddle.net/D2REh/

Q: If a string is a primitive value, why does it have a split() method?
A:
Because any string has a wrapper object that provides numerous methods for that type.
Explanation:
Although primitive JavaScript values do not enjoy the “first-class” nature of objects, they have wrapper objects that temporarily “wrap” the primitive value and provide various methods. Once a primitive wrapper’s method has finished executing, that primitive value is un-wrapped and returned to its normal primitive state.
Helpful Links:

Q: What is the name of the object that refers to the application used to view a web page?
A:
The “navigator” object

Q: Which object.property combination provides a reference to the protocol used to view the current web page?
A:
location.protocol

Q: True or False: The object returned by the document.getElementsByTagName() method is an array
A:
False
Explanation:
The object returned by the document.getElementsByTagName() method is an “HTMLCollection”. This is an array-like object that has a “length” property, can be enumerated, but is not an actual JavaScript array.
Helpful Links:

Scope

Although the concept of scope in JavaScript pertains specifically to the visibility of variables, it is difficult to master object-oriented JavaScript without also mastering scope. The two work hand-in-hand, laying the groundwork for a very powerful and expressive language.
Q: True or False: An object literal can be used to create private variables.
A:
False. Only functions can be used in JavaScript to create privacy
Explanation:
All of the properties of a object literal are public and can be easily mutated. The only way to create private variable in JavaScript is by using a function. You can make a property of an object literal a function (i.e. a “method”), and use private variables in that function, but the named property will always be public.

Q: If you omit the “var” keyword when creating a variable in a function, it becomes a property of what object?
A:
The window object
Explanation:
When omitting the “var” keyword, the variable you create becomes an “implied global”. But implied globals are not variables in a function. An implied global actually becomes a property of the window object. Although the window object is considered the “global” scope, it is an object, and any variable declared in the global scope (intentionally or otherwise), becomes a property of the window object.
Helpful Link:

Context

In JavaScript, context pertains to the object within which a function is executed. Understanding context is a critical step towards writing advanced Object-Oriented JavaScript.
Q: What is the difference between a constructor function and a non-constructor function with respect to the word “this”
A: In a non-constructor function, “this” refers to the global context or if the function is executed inside of another function, it refers to the context of the outer function. In the instance object that is returned by a constructor function, “this” refers to the context of that function.
Explanation: JavaScript constructors are more useful when you understand how they behave differentlyfrom normal JavaScript functions and Object Literals.
Here is a jsFiddle.net example: http://jsfiddle.net/nyFyE/

Passing by Reference vs Passing by Value

It is critical to know whether a variable you are accessing has been passed by reference or value. Not knowing the difference can lead to spaghetti code and odd behavior that is difficult to troubleshoot.
Q:In JavaScript, are objects passed by reference or by value?
A:By reference
Explanation:
In JavaScript, all objects are passed by reference. When you make a change to a reference to an object, you change the actual object. Primitive types are passed by value.
Here is a jsFiddle.net example: http://jsfiddle.net/pmMLc/

Object Mutation

One of the things that makes JavaScript so expressive is its dynamic nature. Objects can be mutated at any time during the execution of your script. Those who come to JavaScript from conventional object-oriented languages such as C++ and Java sometimes find this behavior odd. One you become comfortable to working in this manner, you can start to tap into the deeper aspects of the language.
Q: True or False: Once you create an object, you can add, remove or change properties of that object at any time.
A: True
Here is a jsFiddle.net example: http://jsfiddle.net/n3kR4/

Object Inheritance

JavaScript is a prototype-based language, which means that it differs from conventional object-oriented languages such as Java or C++. For example, when you create an array, it inherits from the Array constructor, which in-turn inherits from Object. You can create your own inheritance chain using the JavaScript prototype object.
Q: What is the name of the property that allows you to add properties and methods to an object, as well as every object that inherits from it?
A: The ‘prototype’ property.
Explanation:

Q: How do you determine if a JavaScript instance object was created from a specific constructor or not?
A: Use the instanceof operator
Helpful links for the JavaScript instanceof operator: