Skip to main content

JavaScript Interview Questions


This is a compilations of all the interview questions related to Javascript that i have encountered. 


Q: Difference between window.onload and onDocumentReady?

A: 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.

Q:  What is the difference between == and === ?

A: The == checks for value equality, but === checks for both type and value.
Few examples:
"1" == 1; // value evaluation only, yields true
"1" === 1; // value and type evaluation, yields false
"1" == true; // "1" as boolean is true, value evaluation only, yields true
"1" === false; // value and type evaluation, yields false

Q: What does “1″+2+5 evaluate to? What about 5 + 2 + “1″?

"1" + 2 + 5; // Since 1 is of type string type priority is given to string all the way, yields "125"
5 + 2 + "1"; // type priority is given to number then string, yields "71" 
 
Q: What are the different data types in Javascript?

A: Boolean, Number, String, undefined, null

Q: What is the difference between undefined value and null value?

A: 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.

Q: How do you change the style/class on any element?

A:
document.getElementById(“myText”).style.fontSize = “20″;
 -or-
 document.getElementById(“myText”).className = “anyclass”;

Q: What are Javascript closures?When would you use them?

A:
 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.

Q: What is unobtrusive javascript? How to add behavior to an element using javascript?

A:
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.

Say an input field with the name “date” had to be validated at runtime: 
<  input name="date" /> 
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.

Q: What is Javascript namespacing? How and where is it used?

A:
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.

Q: What is the difference between innerHTML and append() in JavaScript?

A:
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.

Q: What is the relationship between ECMAScript, Javascript and Jscript?

A:
ECMAScript is the spec for JavaScript and another name for JavaScript
JavaScript is an implementation of the ECMAScript language standard and is primarily used to manipulate the DOM
JScript is a JavaScript dialect MS created


Q: What do parseInt("07"); return?

A:
7

Q: Alert the contents of the bar variable using the foo variable
var foo = "bar";
var bar = "foobar";

A:
alert(eval(foo));

Q: Alert the string “foobar” after a 10 second delay.

A:
setTimeout(function()
{
alert("foobar");
}, 10000);

Q: Create a Person class with public/private/privileged members and methods.

A:
function Person()

{
this.publicMember = "foo";
this.privilegedMethod = function()
{
return privateMethod();
}
var privateMember = "bar";
function privateMethod()
{
return "hello";
}
}

// Public methods
Person.prototype =
{
getDate: function()
{
return new Date();
},

getWorld: function()
{
return "world";
}
}

// Bonus: Public static method
Person.kill = function()
{
return "dead";
}

Q: How would you embed this URL in a link inside an XHTML document?
OR
When you clcik on "XHTML" google search you should go to the following link
http://www.google.com/search?hl=en&q=%22xhtml%22

A:
change & to &
change %22 to "
<   a href="http://www.google.com/search?hl=en&q="xhtml"">"XHTML" google search


Q: How would you serve a StyleSheet only to IE users older than IE8?


A:
<  !– if [ IE < 8 ] –>
< lt style type="text/css" src="iefail.css" />
< !– [ endif ] –>

// or use

< !--[if lt IE 8 ]>[stylesheet here]<![endif]-->

Q: Write a jQuery plugin to display a list of images in a Lightbox.


A:
(function($)
{
$.fn.lightBox = function()
{
//...
return this.each(function()
{
var $this = $(this);
$this.css('border', '1px solid red');
$this.click(function()
{
//...
});
//....
});
}
})(jQuery)

 
Q: Implement Array.prototype.filter for IE.

A:
  if (!('filter' in Array.prototype)) {
Array.prototype.filter= function(filter, that /*opt*/) {
var other= [], v;
for (var i = 0, n = this.length; i < n; i++)
if (i in this && filter.call(that, v = this[i], i, this))
other.push(v);
return other;
};
}

Q: Why does the statement 5 * 1.015 not return 5.075?


A:
JavaScript uses a floating-point number format which cannot store certain numbers “exactly”. In other words, some numbers are approximations. To get precise decimal places use toFixed or Math.round

5 * 1.015 // 5.074999999999999
parseFloat((5 * 1.015).toFixed(3)) // 5.075
parseFloat(Math.round((5 * 1.015) * Math.pow(10,3)) / Math.pow(10,3)) // 5.075

Q: Replace the string "the lazy dog" with the string "the1 lazy2 dog3".

A:
// there are several ways to do this, .split or .replace both have good solutions to this
var statement = "The the lazy dog";
var statement_new = statement.split(' ').map(function(word, index) {
return word + index;
}).join(' ');

// OR

var i = 1,
sta = "The lazy dog";
sta.replace(/\w+/g, function(word) {
return word + i++;
});
 
//another method


'the lazy dog'.split(' ').reduce(function (p, c, i){ return (!+p ? p + ' ' : '') + c + (i + 1) }, 1)
 

Comments

  1. var statement = "The the lazy dog";
    var statement_new = statement.split(' ').map(function(word, index) {
    return word + index;
    }).join(' ');

    This should actually be "return word + (index+1)"
    as index starts at 0.

    ReplyDelete

Post a Comment

Popular posts from this blog

Insufficient access rights to perform the operation. (Exception from HRESULT: 0x80072098)

While accessing the active directory (AD) and authorization manager (AZMAN) , If you get “   Insufficient access rights to perform the operation. (Exception from HRESULT: 0x80072098)  “ message check the    account that is being used to get the LDAP query from AD .  ERROR DETAILS Exception Details:  System.Runtime.InteropServices.COMException: Insufficient access rights to perform the operation. (Exception from HRESULT: 0x80072098) Source Error: Line 154:    'Session("FullName") = System.Security.Principal.WindowsIdentity.GetCurrent.Name.ToString() Line 155: Line 156:    If Not User.IsInRole("Role1") Then Line 157:          Response.Redirect("./Login.aspx") Line 158:    End If  Stack Trace : .... SOLVE IT Steps to do check the app pool rights: Click on the website name that you are having problem with in IIS  In the right panel you will se...

Do's and Don't SQL

Do's: Writing comments whenever something is not very obvious, as it won’t impact the performance.  (--) for single line  (/*…*/) to mark a section Use proper indentation Use Upper Case for all SQL keywords. SELECT, UPDATE, INSERT, WHERE, INNER JOIN, AND, OR, LIKE. Use BEGIN... END block for multiple statements in conditional code  Use Declare and Set in beginning of Stored procedure Create objects in same database where its relevant table exists otherwise it will reduce network performance. Use PRIMARY key in WHERE condition of UPDATE or DELETE statements as this will avoid error possibilities. If User table references Employee table than the column name used in reference should be UserID where User is table name and ID primary column of User table and UserID is reference column of Employee table. Use select column name instead of select * Use CTE (Common Table Expression); its scope is limited to the next statement in SQL query, instead of...