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 === ?

The == checks for value equality, but === checks for both type and value.

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

Since 1 is a string, everything is a string, so the result is 124. In the second case, its 93.

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

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

document.getElementById(“myText”).style.fontSize = “20?;

-or-

document.getElementById(“myText”).className = “anyclass”;

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

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

1

<input type="text" name="date" />

Say an input field with the name “date” had to be validated at runtime:

1

2

3

4

5

6

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.

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

9.  What datatypes are supported in Javascript?

Number, String, Undefined, null, Boolean

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

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

Try it: http://jsfiddle.net/tnajdek/AKxn9/

12. 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’.

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

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

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

}

16. 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)

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

})();

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

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

}

20.What are JavaScript types? 

Number, String, Boolean, Function, Object, Null, Undefined.

21.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);

22.What does "1"+2+3 evaluate to?

Since 1 is a string, everything is a string, so the result is 123.

23.How about 3+5+"8"?

Since 3 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 88 is the result.

24.How do you submit a form using Javascript? 

Use document.forms[0].submit();

25.How do you assign object properties?

obj["age"] = 22 or obj.age = 22.

26.What’s a way to append a value to an array?

arr[arr.length] = value;

27.What does isNaN function do? 

Return true if the argument is not a number.

28.What’s relationship between JavaScript and ECMAScript?

ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3.

29.How to read and write a file using javascript? 

I/O operations like reading or writing a file is not possible with client-side javascript.

30.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 FF to decimal, use parseInt ("FF", 16);

31.What is negative infinity? 

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

32.How to set a HTML document's background color? 

document.bgcolor property can be set to any appropriate color.

33.What boolean operators does JavaScript support?

&&, and !

34.How to get the contents of an input box using Javascript? 

Use the "value" property.

var myValue = window.document.getElementById("textboxID").value;

35.How to determine the state of a checkbox using Javascript? 

var checkedP = window.document.getElementById("CheckBoxID").checked;

36.How to set the focus in an element using Javascript? 

<script> function setFocus() { if(focusElement != null) { document.forms[0].elements["myelementname"].focus(); } } </script>

37.How to access an external javascript file that is stored externally and not embedded? 

This can be achieved by using the following tag between head tags or between body tags.

<script src="raj.js"></script>How to access an external javascript file that is stored externally and not embedded? where abc.js is the external javscript file to be accessed.

38.What is the difference between an alert box and a confirmation box? 

An alert box displays only one button which is the OK button whereas the Confirm box displays two buttons namely OK and cancel.

39.What is a prompt box? 

A prompt box allows the user to enter input by providing a text box.

40.Can javascript code be broken in different lines? 

Breaking is possible within a string statement by using a backslash \ at the end but not within any other javascript statement.

that is ,

document.write("Hello \ world");

is possible but not document.write \

("hello world");

41.What looping structures are there in JavaScript?

for, while, do-while loops, but no foreach.

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

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

43.What is this keyword?

It refers to the current object.

44.What is the difference between SessionState and ViewState? 

ViewState is specific to a page in a session. Session state refers to user specific data that can be accessed across all pages in the web application.

45.What looping structures are there in JavaScript? 

for, while, do-while loops, but no foreach.

46.To put a "close window" link on a page ? 

<a href='javascript:window.close()' class='mainnav'> Close </a>

47.How to hide javascript code from old browsers that dont run it? 

Use the below specified style of comments <script language=javascript> <!-- javascript code goes here // --> or Use the <NOSCRIPT>some html code </NOSCRIPT> tags and code the display html statements between these and this will appear on the page if the browser does not support javascript

48.How to comment javascript code? 

Use // for line comments and

/*

*/ for block comments

49.Name the numeric constants representing max,min values 

Number.MAX_VALUE

Number.MIN_VALUE

50.What does javascript null mean? 

The null value is a unique value representing no value or no object.

It implies no object,or null string,no valid boolean value,no number and no array object.

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

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

52.How do you assign object properties? 

obj["age"] = 23 or obj.age = 23.

53.What’s a way to append a value to an array? 

arr[arr.length] = value;

54.To set all checkboxes to true using JavaScript? 

//select all input tags

function SelectAll() {

var checkboxes = document.getElementsByTagName("input");

for(i=0;i<checkboxes.length;i++) {

if(checkboxes.item(i).attributes["type"].value == "checkbox") {

checkboxes.item(i).checked = true;

}

}

}

55.What does undefined value mean in javascript? 

Undefined value means the variable used in the code doesn't exist or is not assigned any value or the property doesn't exist.

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

(i)Undefined value cannot be explicitly stated that is there is no keyword called undefined whereas null value has keyword called null

(ii)typeof undefined variable or property returns undefined whereas typeof null value returns object

57.What is variable typing in javascript? 

It is perfectly legal to assign a number to a variable and then assign a string to the same variable as follows

example

i = 10;

i = "string";

This is called variable typing

58.Does javascript have the concept level scope? 

No. JavaScript does not have block level scope, all the variables declared inside a function possess the same level of scope unlike c,c++,java.

59.What are undefined and undeclared variables? 

Undeclared variables are those that are not declared in the program (do not exist at all),trying to read their values gives runtime error.But if undeclared variables are assigned then implicit declaration is done .

Undefined variables are those that are not assigned any value but are declared in the program.Trying to read such variables gives special value called undefined value.

60.What is === operator ? 

==== is strict equality operator ,it returns true only when the two operands are having the same value without any type conversion.

61.How to disable an HTML object ?

document.getElementById("myObject").disabled = true;

62. How to create a popup warning box?

alert('Warning: Please enter an integer between 0 and 1000.');

63.How to create a confirmation box? 

confirm("Do you really want to launch the missile?");

64.How to create an input box? 

prompt("What is your temperature?");

65.How to force a page to go to another page using JavaScript ? 

<script language="JavaScript" type="text/javascript" >

66.What's Math Constants and Functions using JavaScript? 

The Math object contains useful constants such as Math.PI, Math.E

Math.abs(value); //absolute value

Math.max(value1, value2); //find the largest

Math.random() //generate a decimal number between 0 and 1

Math.floor(Math.random()*101) //generate a decimal number between 0 and 100.

67.What does the delete operator do? 

The delete operator is used to delete all the variables and objects used in the program ,but it does not delete variables declared with var keyword.

68.How to get value from a textbox?

alert(document.getElementById('txtbox1').value);

69.How to get value from dropdown (select) control?

alert(document.getElementById('dropdown1').value);

70. How do you write an event emitter base class that allows you to add event listeners?

This question can nicely lead into architectural questions, Huckestein says, such as: “How would you make an event emitter that’s distributed?”

71. What is the concept of “functions as objects” and how does this affect variable scope?

New hires at Vector Media Group are asked this mid-level question, says Matt Weinberg, president of development and technology at Vector, a web development and Internet marketing agency in Manhattan.

“What it can suggest is that the person really ‘gets’ JavaScript and the way it works as opposed to just having copied syntax and code from the web without understanding it,” Weinberg says. “It can also show that the person has at least some understanding of basic programming concepts, which in my experience means they will be better equipped to come up with good solutions to hard problems.”

72. What is the difference between .call() and .apply()?

The JavaScript Function prototype has two very powerful functions that are at the core of Javascript’s “everything is an object” mentality, including functions, Kubasik says.

“The really important part of this discussion is not that they remember which is which, but more that the interviewee understands that the “this” keyword is not as predictable as in other languages, and that functions can be applied to other objects, and generally be treated as data,” he says.

73. Can you explain how inheritance works in JavaScript?

JavaScript has a somewhat unique inheritance model and a good understanding of it is crucial to using JavasScript in larger applications, Kubasik says.  “We are looking for the applicant to discuss not only prototypes, and how that affects inheritance, but in what ways this can be more flexible than classical inheritance models seen in Java and C#.”

74. What is event bubbling in the DOM?

The main goal of this question is to establish that the applicant knows what order events will be propagated in the DOM – most specific to least specific.

“Not everyone may know this by the name ‘event bubbling,’ so asking about event propagation in general is sometimes needed. Ideally, this is an opportunity to discuss event models outside of the DOM, and ask follow-up questions about routing based on user actions, looking for techniques popularized with frameworks like backbone.js, or AngularJS,” Kubasik says.

Blake Haggerty, Rackspace’s lead recruiter in San Francisco, says that beyond specific questions, recruiters have other resources for assessing candidates’ skills with JavaScript.

“I can go onto GitHub or BitBucket. I can actually look at what they’ve done with their code. I can see the projects they’ve worked on [and] I can see how much they’ve contributed to projects. I can go onto sites like Stack Overflow and see who are the influential people in the community, see who’s answering questions specifically about JavaScript,” he says. “… from that I already know they’re technically savvy, so from there, my role is just to convince them to leave where they currently are and come work for us.”

75.How to get value from a textbox?

alert(document.getElementById('txtbox1').value);

76. How to get value from dropdown (select) control.?

alert(document.getElementById('dropdown1').value);

77.How to get value from RadioButtonList control?

Here id is the name property of the RadioButtonList

function GetRadioButtonValue(id)

        {

            var radio = document.getElementsByName(id);

            for (var ii = 0; ii < radio.length; ii++)

            {

                if (radio[ii].checked)

                    alert(radio[ii].value);

            }

        }

For more details, click http://www.dotnetfunda.com/articles/article72.aspx

78.How to get CheckBox status whether it is checked or not?

Write following code

alert(document.getElementById('checkbox1').checked);

if it will be checked you will get true else false.

79.How to toggle display an HTML element?

Call following function

function ToggleFollowingText(id)

        {

            document.getElementById(id).style.display == '' ? document.getElementById(id).style.display =

 'none' : document.getElementById(id).style.display = '';

        }

In above function you need to pass id of the html element as the parameter.

If the control is already displaying then it will hide otherwise it will be shown.

80.What is undefined value means in JavaScript?

There can be multiple reasons of having undefined values

1. Object does not exist. Like you create an object of a control which does not exists in your page and when you access it, it is undefined.

2. No value is assigned to the object.

3. If you are trying to access a property which does not exists for the object.

81.Is it possible make a call to server side event of any button using javascript?

Yes, it's possible. You can use __doPostBack() function to call server side event.

Q.What is other equivalent option of document.getElementById() when you are working with Ajax?

The other equivalent option of document.getElementById() is $get() ;.

For example.

var x =  $get('<%= upnlScoping.ClientID %>'); 

var y = document.getElementById('<%= upnlScoping.ClientID %>');

82.How can you set position of the page (Top and Left) to 0 using Javascript in one line code?

Well, there is an inbuilt function in JavaScript named scroll() which takes 2 arguments x and y.

If you want to set top and left to 0 then call this.

window.scroll(0,0);

83.What is the result of below given line of code in Java Script? 5+4+'7'

The answer is 97.

As 5 and 4 are integer so total becomes 9 and it's add '7' to it as string so it becomes 97.

84.Name the DataTypes of JavaScript?

1)Integer

2)String

3)Boolean

4)Null

85.Write a way by which you can do something on the close of the window ?

call onUnload on the body tag and write your javascript code there

e.g:

<body onUnload=''alert('thanks for visiting us !!')">

86.How to create an Object in JavaScript ?

1) var obj = new Object();

2) var ob = {};

87.Basic methods for opening a PopUp window using Javascript?

There are 2 different simple ways using javascript.

they are

1) Using Window.Open() and

2) Using Window.showModalDialog()

The Syntax for using these methods are

=> Window.Open(URL,WindowName,Window Features)

Sample example:

window.open ("http://www.atoztarget.com","mywindow","status=1,toolbar=1");

=> window.showModalDialog(URL,WindowName,ModalDialog Features)

Sample Example:

window.showModalDialog("http://www.dotnetfunda.com", "mywindow","dialogWidth:400px;dialogHeight:395px");

88.What is JSON?

JSON is nothing but a JavaScript Object Notation . It is language independent and derived from Java Script. 

This is a LightWeight scripting language designed for data interchange over a network. Basically this is used for data serialization and data transmission which helps to transfer data between the server and the web application.

89.How can you detect the Client Operating System using Javascript?

just type this command in a .html file

<script>

alert(window.navigator.appVersion);

</script>

90.What is the data type of variables in JavaScript?

Javascript is a weakly typed language:It does not use int, string, DateTime etc

as the datatype with the variables declaration as we do in c#.

variables are declared using the var keyword which can accept any data.

91.What is negative infinity?

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

Code snippet

<script>

var a=-45;

alert(a/0);

</script>

output:

-Infinity

92.if 2 methods have same name and same number of parameters, which one will be executed first?

The second method will be executed first

Code snippet.

<script>

function demo(s)

{

alert("first"+"---"+s);

}

function demo(s)

{

alert("Second"+"--"+s);

}

demo("javascript");

demo("jscript");

demo("jp");

</script>

output:

//In this example, the function with alert("Second"+"---"+s); statement will

//be executed 3 times, while the first function will not execute at all.

93.Difference between undefined and undeclared variables.

Undefined variables are those that are not assigned any value but declared in the program.

if we try to read the value, an error message "undefined" is displayed.

undeclared variables are those that are not declared in the program .

if we try to read their values gives runtime error.

But if undeclared variables are assigned some value then implicit declaration is done .

example:

<script>

//a is undefined variable

var a;

alert(a);

//b is undeclared variable

alert("hello"+"--"+b);

</script>

A:-undefined:

B:-will also be undefined but that error message can be seen by clicking in browser

status bar: if some value is assigned to b, then it will be displayed in the output.

94.Difference Json Arrary Vs Json Object ?

JSONArray

A JSONArray is an ordered sequence of values. Its external text form is a string wrapped in square brackets with commas separating the values.

[        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},

        {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},

        {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}

]

JSONObject

A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names.

{"bindings": [

        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},

        {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},

        {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}

  ]

};

95.What is the difference of "setTimeout" function and setInterval functions in Javascript

setTimeout is only execute the function after the defined time in milleseconds, its execute only one time.

setInterval, will call the function in each time interval.

96.What is the difference between the below two statements:- (1) var myname = "Akiii"; (2) myname = "Akiii";

Both the above two statements are same. In javascript, even if you don't declare a "var" keyword, it is automatically added.

Note:-

It is always good to use "var" to declare any variable in javascript. It makes the code cleaner and readable.

97.What data type javascript supports?

Javascript supports only object data type.

Example

var variablename; //var is an object

98.What is isNaN in javascript?

isNaN is a function, it returns true if the argument is not a number.

Example:

var a="text";

var b=1234;

document.write(isNaN(a)) //it will return true

document.write(isNaN(b)) //returns false

99.How will you create new object in javascript?

In object variable, you can pass any value like stirng, integer.

var obj=new Object();

obj="my string";

document.write(obj);

100.How do you create array in javascript?

var arr=new Array();

arr[0]="dot";

arr[1]="net";

arr[2]="funda";

document.write(arr[0] + " " + arr[1] + " " + arr[2]);