Choose.. X Home Exams Certifications

Javascript Interview Questions

1 . Difference between window.onload and onDocumentReady?

  • The onload event does not fire until every last piece of the page is loaded, this includes css and images, which means there's a huge delay before any code is executed.
    That isnt what we want. We just want to wait until the DOM is loaded and is able to be manipulated. onDocumentReady allows the programmer to do that.

2 . What is the difference between == and ===? Which one would you use?

  • The == checks for value equality, but === checks for both type and value.
    The equality == operator will compare for equality after doing necessary type casting, the identity operator === doesn't do any conversions.

3 . 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"

4 . What does "2"+3+1 evaluate to? What about 4 + 3 + "3"?

  • Since 2 is a string, everything is a string, so the result is 231. In the second case, its 73.

5 . What is the difference between undefined value and null value?

  • undefined means a variable has been declared but has not yet been assigned a value.
    On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value.
    Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.
    Unassigned variables are initialized by JavaScript with a default value of undefined.
    JavaScript never sets a value to null,that must be done programmatically.

6 . How do you change the style/class on any element?

  • document.getElementById("myText").style.fontSize = "20";
    document.getElementById("myText").className = "anyclass";

7 . What are Javascript closures?When would you use them?

  • Two one sentence summaries:
    * a closure is the local variables for a function - kept alive after the function has returned, or
    * a closure is a stack-frame which is not deallocated when the function returns.
    A closure takes place when a function creates an environment that binds local variables to it in such a way that they are kept alive after the function has returned.
    A closure is a special kind of object that combines two things: a function, and any local variables that were in-scope at the time that the closure was created.
    The following code returns a reference to a function:
    function sayHello2(name) {
    var text = 'Hello ' + name; /* local variable*/
    var sayAlert = function() { alert(text); }
    return sayAlert;
    Closures reduce the need to pass state around the application. The inner function has access to the variables in the outer function so there is no need to store the information somewhere that the inner function can get it.
    This is important when the inner function will be called after the outer function has exited. The most common example of this is when the inner function is being used to handle an event.
    In this case you get no control over the arguments that are passed to the function so using a closure to keep track of state can be very convenient.

8 . What is unobtrusive javascript? How to add behavior to an element using javascript?

  • Unobtrusive Javascript refers to the argument that the purpose of markup is to describe a document's structure, not its programmatic behavior and that combining the two negatively impacts a site's maintainability.
    Inline event handlers are harder to use and maintain, when one needs to set several events on a single element or when one is using event delegation.
    <input name="date" type="text" />
    Say an input field with the name "date" had to be validated at runtime:
    document.getElementsByName("date")[0].addEventListener("change", validateDate, false);
    function validateDate(){
    /* Do something when the content of the 'input' element with the name 'date' is changed.*/

    Although there are some browser inconsistencies with the above code, so programmers usually go with a javascript library such as JQuery or YUI to attach behavior to an element like above.

9 . What is Javascript namespacing? How and where is it used?

  • Using global variables in Javascript is evil and a bad practice. That being said, namespacing is used to bundle up all your functionality using a unique name.
    In JavaScript, a namespace is really just an object that you've attached all further methods, properties and objects. It promotes modularity and code reuse in the application.

10 . What datatypes are supported in Javascript?

  • String, Number, Boolean, Array, Object, Null, Undefined.
    JavaScript has dynamic types. This means that the same variable can be used as different types:
    var x;                /* Now x is undefined*/
    var x = 5;   /* Now x is a Number*/
    var x = "John";   /* Now x is a String*/

11 . How is form submission possible via javascript?

  • We can achieve the desired form submission by using the function document.forms[0].submit().
    It must be noted that the 0 in the piece of code given above refers to the form index.
    Say we have multiple forms on a particular page. To make all the form procession unique, we give each form index numbers. The first form will have the index number as 0. The second form will have an incremented number, 1. The third will have 2 and so on.

12 . How JavaScript timers work? What is a drawback of JavaScript timers?

  • Timers allow you to execute code at a set time or repeatedly using an interval.
    This is accomplished with the setTimeout, setInterval, and clearInterval functions.
    The setTimeout(function, delay) function initiates a timer that calls a specific function after the delay; it returns an id value that can be used to access it later.
    The setInterval(function, delay) function is similar to the setTimeout function except that it executes repeatedly on the delay and only stops when cancelled.
    The clearInterval(id) function is used to stop a timer. Timers can be tricky to use since they operate within a single thread, thus events queue up waiting to execute.

13 . How to detect the operating system on the client machine?

  • In order to detect the operating system on the client machine, the navigator.appVersion string (property) should be used.

14 . What is the difference between innerHTML and append() in JavaScript?

  • InnerHTML is not standard, and its a String.
    The DOM is not, and although innerHTML is faster and less verbose, its better to use the DOM methods like appendChild(), firstChild.nodeValue, etc to alter innerHTML content.

15 . What boolean operators does JavaScript support?

  • &&, || and !

16 . What is negative infinity?

  • It's a number in JavaScript, derived by dividing negative number by zero.

17 . Is it possible to check if a variable is an object?

  • Yes, it is possible to do so. The following piece of code will help achieve the same.
    if(abc && typeof abc === "object") {
    console.log('abc is an object and does not return null value');

18 . Can you explain what isNaN function does?

  • isNaN function will check an argument and return true if the argument does not seem to be a number.

19 . How do you convert numbers between different bases in JavaScript?

  • Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter.
    So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16);

20 . Differentiate between "var a=2" and "a =2"

  • The major difference between the two is that one variable is local and the other is global. "var" basically defines the scope of the variable.
    When we add var to a variable value assignment, javascript ensures that the variable is confined to whichever function it is assigned to and does not collide with the same name variable within another function.
    When we don't use var, then it is declared as a global function and chances of collision can happen. So it's always advisable to use "var" before variable value assignment. If needed use an anonymous function for closure.

21 . What is Javascript namespacing? How and where is it used?

  • Using global variables in Javascript is a bad practice. That being said, namespacing is used to bundle up all your functionality using a unique name.
    In JavaScript, a namespace is really just an object that you've attached all further methods, properties and objects. It promotes modularity and code reuse in the application.

22 . How to create arrays in JavaScript?

  • We can declare an array like this
    var scripts = new Array();

    We can add elements to this array like this
    scripts[0] = "PHP";
    scripts[1] = "ASP";
    scripts[2] = "JavaScript";
    scripts[3] = "HTML";

    Now our array scrips has 4 elements inside it and we can print or access them by using their index number. Note that index number starts from 0.
    To get the third element of the array we have to use the index number 2 . Here is the way to get the third element of an array.
    We also can create an array like this
    var no_array = new Array(21, 22, 23, 24, 25);

23 . How do you create a new object in JavaScript?

  • var obj = new Object();
    var obj = {};

24 . How do you assign object properties?

  • obj["age"] = 17
    obj.age = 17

25 . What's a way to append a value to an array?

  • arr[arr.length] = value;

26 . What is this keyword?

  • It refers to the current object.

27 . How many looping structures can you find in javascript?

  • If you are a programmer, you know the use of loops. It is used to run a piece of code multiple times according to some particular condition. Javascript being a popular scripting language supports the following loops
    • for
    • while
    • do-while loop

28 . Are javascript and jQuery different?

  • jQuery is a quick as well as concise JavaScript Library that simplifies HTML document traversing, animating, event handling, & Ajax interactions for the purpose of quick web development needs. So although they are not entirely different, both are not the same either!

29 . Explain the strict mode in Javascript.

  • The strict mode ensures that if functions are not properly thought it, those are disabled. It also kept a check on potentially unsafe actions and throw errors when it happens.

30 . Is it possible for you to write a one line JavaScript code that concatenates all strings passed into a function?

  • The following function should help in producing the desired result
    function concatenate() 
    return String.prototype.concat.apply('', arguments);

31 . What is event bubbling?

  • Event bubbling describes the behavior of events in child and parent nodes in the Document Object Model (DOM); that is, all child node events are automatically passed to its parent nodes.
    The benefit of this method is speed, because the code only needs to traverse the DOM tree once.
    This is useful when you want to place more than one event listener on a DOM element since you can put just one listener on all of the elements, thus code simplicity and reduction.
    One application of this is the creation of one event listener on a page's body element to respond to any click event that occurs within the page's body.

32 . 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

33 . 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.
    Async is another attribute that can affect how a script is loaded and executed.
    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.

34 . 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');

35 . 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;
    console.log(foo); /*outputs 1*/
    if(true) {
    var foo = 3; /*redeclares foo*/
    console.log(foo); /*outputs 3*/

36 . 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() {
    /*variable declaration is hoisted but value assignment stays here*/
    var bar = 1;
    baz = 2; /*defines baz in global scope*/

37 . What are closures?

  • A basic overview of javascript closures is that it is a stack-frame which is not de-allocated when the function returns.
    A closure lets you associate some data (the environment) with a function that operates on that data. This has obvious parallels to object oriented programming, where objects allow us to associate some data (the object's properties) with one or more methods.
    (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.

38 . Explain Inheritance Using the Prototype Property

  • Prototype is an internal object from which other objects inherit properties.
    Its main purpose is to allow multiple instances of an object to share a common property.
    Thus, object properties which are defined using the prototype object are inherited by all instances which reference it.
    Ex : You add a method to MyObject (that's the object, not the instance) called doSomething().
    Would that cause new instances of MyObject to inherit the doSomething() method? No it would not.
    What that would do is create a static method that can be called without first instantiating the object (useful to know in itself!).
    Likewise, a function that is added to an instance would only apply to that particular instance.
    Only when the function is assigned to the MyObject.prototype is it inherited by all instances of that Object, including those we instantiated before the creation of the new function:
    MyObject.doSomething = function() {
    alert("I do as I am told.");

    var anotherObject = new MyObject();
    anotherObject.doSomething = function() {
    alert("I do the bare minimum required of me!");

    anotherObject.doSomething(); /*calls the instance specific method*/
    MyObject.doSomething(); /*calls the static Object method*/
    MyObject.prototype.doSomething = MyObject.doSomething; /*apply the static method to all instances from here on in*/
    anotherObject.doSomething(); /*still calls the instance method*/
    var yetAnotherObject = new MyObject();
    yetAnotherObject.doSomething(); /*inherited doSomething() from MyObject*/
    myObject.doSomething(); /*pre-existing instances also inherit the new function*/

39 . 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() {
    var customObject = Object.create(genericObject); = "Aloha folks!";
    console.log(customObject.get_bar()); /*outputs: "Aloha folks"*/
    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

40 . Explain Overriding Pre-existing JavaScript Methods

  • The general rule is that you can prototype any object that's initialized with the "new" keyword, and that includes native JavaScript objects, such as Arrays, Dates, Strings, Functions, and even the generic Object itself.
    In the following example, a function that returns the function name has been added to the Function prototype. An especially good use for this function is to get a function's own name.
    The arguments.callee references the function object, so applying our functionName() function to it returns the function's name:
    Function.prototype.functionName = function()
    var name=/W*functions+([w$]+)(/.exec(this);
    return name?name[1]:'Anonymous';

    function helloWorld() {
    alert('Hello from the '+arguments.callee.functionName()+'() function!');

    helloWorld(); /*displays "Hello from the helloWorld() function!"*/

    Our final example of the day demonstrates how to extend an existing method's functionality by reusing it.
    There are two snippets of code below. The first is a typical overridden Array join() function that I took off an online forum.
    The only difference between it and the original is that the default separator has been changed. Nonetheless, the contributors of the forum advocated completely rewriting the original join() method.
    If you ask me, replacing tried and true code with your own is just asking for bugs! A far better way is to use a closure to store the original method and add your own functionality to it:
    /*a complete (and unnecessary) rewrite*/
    Array.prototype.join = function(separator) {
    if (separator == undefined) {separator = '|'}
    var text = new String();
    for (obj in this) {
    text += this[obj] + separator;
    return text;

    /*a better way that reuses the existing functionality*/
    Array.prototype.join = (function(originalJoin) {
    return function(separator) { return, separator===undefined?separator:'|'); };

    alert( [1,2,3,4,5].join() ); /*uses the default: displays "1|2|3|4|5"*/
    alert( [1,2,3,4,5].join('') ); /*no separator: displays "12345"*/
    alert( [1,2,3,4,5].join(' * ') ); /*custom separator: displays "1 * 2 * 3 * 4 * 5"*/

41 . 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 ...*/