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 see 'Basic Settings'. Click It. Select the specific pool option and enter the name of the ac

Sql Server database Read_Only / Read_Write

The ALTER DATABASE command allows a database administrator to modify SQL Server databases and their files and filegroups. This includes permitting the changing of database configuration options. Why Read Only ? When you need to ensure that the data is a database is not modified by any users or automated processes, it is useful to set the database into a read-only mode. Once read-only, the data can be read normally but any attempts to create, updated or delete table rows is disallowed. This makes the read-only mode ideal when preparing for data migration, performing data integrity checking or when the data is only required for historical reporting purposes. Make Database Read Only USE  [master] GO ALTER DATABASE  [TESTDB]  SET  READ_ONLY  WITH  NO_WAIT GO Make Database Read/Write USE  [master] GO ALTER DATABASE  [TESTDB]  SET  READ_WRITE  WITH  NO_WAIT GO In case you get the following error message make the database single user: Msg 5070, Level 16, Stat

Query Active Directory from SSMS - 3 steps

Step1: Get the Servers Run the following command to get the list of all linked servers. sp_linkedservers Note: sp_helpserver can also be used to list the available servers Step 2: Add the server you want to connect to [This is important, because most people mess up here] To add a linked server we will use the following command sp_addlinkedserver EXEC sp_addlinkedserver @server=N'S1_instance1', @srvproduct=N'', @provider=N'SQLNCLI', @datasrc=N'S1\instance1'; Step 3: Query the Active Directory DECLARE @Application TABLE (cn varchar(50)); DECLARE @ApplicationCN varchar(50); DECLARE @SQLString nvarchar(MAX); DECLARE @ApplicationName varchar(20)= 'yy' -- name of the container DECLARE @Role varchar(20) = 'xxx' DECLARE @Domain nvarchar(20) = 'a.com' -- if this is a.com SET @SQLString='SELECT cn FROM OPENQUERY(ADSI,''SELECT cn FROM ''''LDAP://' +@Domain +''''