Javascript Interview Questions and Answers..

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.

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

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

Q.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
 
Q.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"
 
Q.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');
}
Q.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)

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

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

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

Q.What are JavaScript types? 
Number, String, Boolean, Function, Object, Null, Undefined.

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

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

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

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

Q.How do you submit a form using Javascript? 
Use document.forms[0].submit();

Q.How do you assign object properties?

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

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

arr[arr.length] = value;

Q.What does isNaN function do? 

Return true if the argument is not a number.

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

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

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

Q.What is negative infinity? 

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

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

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

Q.What boolean operators does JavaScript support?

&&, and !

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

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

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

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

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

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

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

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

Q.What is a prompt box? 

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

Q.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");

Q.What looping structures are there in JavaScript?

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

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

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

Q.What is this keyword?

It refers to the current object.


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


Q.What looping structures are there in JavaScript? 

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

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

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

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

Q.How to comment javascript code? 

Use // for line comments and
/*
*/ for block comments

Q.Name the numeric constants representing max,min values 

Number.MAX_VALUE
Number.MIN_VALUE

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

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

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

Q.How do you assign object properties? 

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

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

arr[arr.length] = value;


Q.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;
}
}
}

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

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

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

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

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

Q.What is === operator ? 

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


Q.How to disable an HTML object ?

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

How to create a popup warning box?

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

Q.How to create a confirmation box? 

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

Q.How to create an input box? 

prompt("What is your temperature?");

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

<script language="JavaScript" type="text/javascript" ><!-- location.href="http://rajeshstutorials.blogspt.com"; //--></script>

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

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

Q.How to get value from a textbox?

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

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

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

Q: How do you implement an extend function that takes an object and extends itwith new properties and makes it work on n levels of recursion? Basically, duplicating a jQuery extend. 

This question shows whether candidates have an understanding of basic programming concepts such as recursion, says Jonas Huckestein, co-founder of conference-calling startup HipDial.

Q: Can you write a function that takes an object and appends it to the DOM, making it so that events are buffered until the next tick? Explain why this is useful?

This last part only applies in browser-side settings where it can dramatically increase performance, he says.

Q: 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?”

Q: 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.”

Q: What modern JavaScript frameworks and utilities excite you right now from an approach and code point of view, even if they’re not yet stable enough for client work?

“I’m less concerned with the actual answers, though there are some frameworks I’m very interested in,” Weinberg says. “[I’m] more concerned with knowing that they keep up to date on the latest thinking around JavaScript.”
Weinberg added: “When they explain what excites them about these frameworks or utilities, I can get a good sense of the kind of work and style they prefer.”
Kubasik is also concerned about the flood of “copy-and-paste” JavaScript solutions.
“jQuery and its plugin system are so popular that many developers only know JavaScript in that context, and have trouble understanding how to create new functionality,” Kubasik says. “While this is fine for many websites, which only need a dynamic menu or homepage carousel, as the emerging web becomes more “stateful” – (he points to USA Today’s redesign as an example of pages that users navigate without loading a new page) – this knowledge becomes crucial to developing robust and maintainable applications.”

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

Q: 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#.”

Q: 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.”


Q.How to get value from a textbox?

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

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

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

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

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

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

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

Q.What is === operator in JavaScript and how it is different from == operator?

=== operator checks for the equality. It gives true when both the compared values are having same value and same data type As === does not perform any type conversion while comparing.

It is different from == as == does the type conversion while comparing. 

Q.Can Javascript code be broken in different lines?

Yes,
Breaking is possible within a string statement by using a backslash "\" at the end .
Ex:
document.write("Good Morning. \
I am Mr. John");

But it is not possible within any other javascript statement.

Ex :
is possible but not
document.write \

Q.How to get the Scroll height and Width in JavaScript !!

Width : window.pageXOffset ||
document.body.scrollLeft ||
document.documentElement.scrollLeft;

Height: window.pageYOffset ||

document.body.scrollTop ||
document.documentElement.scrollTop;

Q.What is undefined variable?

Variables which are declared but not assigned any value is called undefined variable.

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

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

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

Q.Name the DataTypes of JavaScript?


1)Integer

2)String

3)Boolean

4)Null

Q.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 !!')">

Q.How to create an Object in JavaScript ?

1) var obj = new Object();
2) var ob = {};

Q.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.dotnetfunda.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");

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

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

just type this command in a .html file
<script>

alert(window.navigator.appVersion);

</script>

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

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

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

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

Q.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.*"}
    ]
};

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

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

Q.What data type javascript supports?

Javascript supports only object data type.
Example
var variablename; //var is an object

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

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

Q.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]);

Q.How will you sort an array using javascript?

Using sort() function.
var arr=new Array();
arr[0]="dot";
arr[1]="net";
arr[2]="funda";
arr.sort();
document.write(arr[0] + " " + arr[1] + " " + arr[2] );

output will be dot funda net

Q.How to convert a string to float or number in javascript?

parseFloat() and parseInt() are the function to convert string to float and integer respectively.
Example:

parseInt("123.25");

parseFloat("123.25");

Q.How will you submit form using javascript?

Using following line of code:

<script language="javascript">

documnet.formID.submit();

</script>

<form id="formID">

//your from controls here.....

</form>

Q.How Will You Get Textbox Value in Javascript?

By Using This javascript Code ,We Can Get The Textbox Value...
var txt_value= document.getElementById('<%=TextBox1.ClientID%>').value; 

Q.How many different ways XSS attacks can occur?

XSS attacks can be categorized into following three categories:
1) Stored: The attack is saved into a persistent storage medium such as a database or file.
2) Reflected: Non-persistent attacks needing a delivery method to initiate the attack such an email or malicious form.
3) DOM based XSS: This attack manipulates the DOM to execute the attack payload. It is less well known.

Q.How to write in browser page using javascript?

Using following lines of code:


<script type="text/javascript">
document.write("Hi, This is my page.");
</script>

Q.How to change a label value using javascript?

Using following codes 

<script type="text/javascript">
document.getElementById("labelID").innerHTML="Changed Label";
</script>

Q.What is knockout ?

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.
Any time you have sections of UI that update dynamically, KO can help you implement it more simply and maintainable.
It works with any server or client-side technology.
Browser support : (IE 6+, Firefox 2+, Chrome, Safari, others)

Q.What is Chakra ?

It is a new javaScript engine developed by Microsoft for its IE9 web browser.
A distinctive feature of the engine is that it include a new JavaScript compiler that compiles the scripts on a separate CPU core and convert into high-quality native machine code.
The engine is also able to access the computer's graphics processing unit (GPU), in particular for 3D graphics and video.
It also include a new interpreter for executing script on traditional web pages, and improvements to the JavaScript runtime 

and libraries.

Q.what is node.js ?

Node.js is an open-source server-side JavaScript platform for building high performance scalable network program.
It is built on Chrome's V8 JavaScript runtime and the framework is also using other two open source projects like libev and libeio.
It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive

 real-time applications that run across distributed devices.

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

JavaScript has both strict and type-converting equality comparison. For strict equality the objects being compared must have the same type and also the below characteristics:

• Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.

• Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal 

to anything, including NaN. Positive and negative zeros are equal to one another.
• Two Boolean operands are strictly equal if both are true or both are false.
• Two objects are strictly equal if they refer to the same Object.
• Null and Undefined types are == (but not ===).
Example:
== is equal to
=== is exactly equal to (value and type)
0==false // true
0===false // false, because they are of a different type
1=="1" // true, auto type coercion
1==="1" // false, because they are of a different type

Q.What is a javascript object ?

An object is a special kind of data, with a collection of properties and methods.
Let us discuss an example to have a clear idea:
A person is an object. Properties are the values associated with the object. The persons' properties include name, 

height, weight, age, skin tone, eye color, etc. All persons have these properties, but the values of those properties will differ 
from person to person.
Objects also have methods. Methods are the actions that can be performed on objects. The persons' methods could 

be eat(), sleep(), work(), play(), etc.
The syntax for accessing a property of an object is:


objName.propName

Example:


personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=30;
personObj.eyecolor="blue";
document.write(personObj.firstname);
You can call a method with the following syntax:
objName.methodName()
Example:
personObj.sleep();

Q.How do you submit a form using Javascript ?

By using below snippet, we can submit a form using Javascript.

Use document.forms[0].submit();
Here, in the above snippet, 0 refers to the index of the form – if you have more than one form in a page, then the first one
 has the index 0, second has index 1 and so on.

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

In order to detect the operating system on the client machine, your script can analyze the value of navigator.appVersion or navigator.userAgent.
Example:


// This script sets OSName variable as follows:

// "Windows"    for all versions of Windows

// "MacOS"      for all versions of Macintosh OS

// "Linux"      for all versions of Linux

// "UNIX"       for all other UNIX flavors 

// "Unknown OS" indicates failure to detect the OS

var OSName="Unknown OS";

if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";

if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";

if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";

if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";

document.write('Your OS: '+OSName);
On your system, this script yields the following result:
Your OS: Windows

Q.What is the importance of the HTML DOCTYPE ?

The doctype declaration should be the first thing in an HTML document, before the html tag.
The doctype declaration is not an HTML tag; it is an instruction to the web browser about what version of the markup language the page is written in.
The doctype declaration refers to a Document Type Definition (DTD). The DTD specifies the rules for the markup language,

 so that the browsers can render the content correctly.

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

By using the parseInt() function, we can convert numbers between different bases in JavaScript. This function takes a string 
as the first parameter, and the base as a second parameter.
Example:
To convert hexadecimal 3F to decimal, we use
parseInt ("3F", 16);

Q.What is the difference between GET and POST in HTML forms ?

The differences between both are described as follows:
GET: Parameters are passed in the querystring. This method appends the form-data to the URL in name/value pairs.

 Maximum amount of data that can be sent via the GET method is limited to about 2kb. Never use the "get" method to pass sensitive information! (password or other sensitive information will be visible in the browser's address bar).
POST: Parameters are passed in the request body. This method sends the form-data as an HTTP post transaction. 

There is no limit to the amount of data that can be transferred using POST. However, there are limits on the maximum amount of data that can be transferred in one name/value pair.
For example, go through the below link.

Q.What does the "Access is Denied" IE error mean ?

The "Access Denied" error in any browser is due to the following reason:
If a javascript in one window or frame tries to access another window or frame whose document's domain is different from 

the document containing the script, then this error occurs.

Q.What is Modernizr ?

It is an open-source JavaScript library that helps you build the next generation of HTML5 and CSS3-powered websites.
It provides a more modern way to test features that a browser supports and can even handle loading additional scripts called shims or polyfills that fill in holes that older browsers may have.
Two different types of scripts are available, one for a development script and custom production script.

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

By using the "value" property, you can get the contents of an input box.
Example:

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

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

To determine the state of a checkbox using Javascript, you can use the following example.
Example:

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

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

Following are the basic diferences between undefined value and null value.
(i)Undefined value cannot be explicitly stated i.e., there is no keyword called undefined whereas null value has keyword called null.
(ii)Typeof undefined variable or property returns undefined whereas type of null value returns object.

Q.What is the use of eval() in javascript ?

The eval() method is allows you to execute code snippets during execution.
Example:


<script type="text/javascript">

var USA_Texas_Austin = "521,289";

document.write("Population is "+eval("USA_"+"Texas_"+"Austin"));

</script>

This produces
Population is 521,289. 

Q.How to create a function using function constructor ?

The following example gives detailed explanation on this:
Example:
It creates a function called square with argument x and returns x multiplied by itself.

var square = new Function ("x","return x*x");

Q.What is Backbone.js ?

It gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
It is data binding framework.

Q.What is BSON ?

Bin­ary JSON (BSON), is a bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments.
Like JSON, BSON sup­ports the em­bed­ding of doc­u­ments and ar­rays .
BSON also con­tains ex­ten­sions that al­low rep­res­ent­a­tion of data types that are not part of the JSON specification.
Its main features are Lightweight,Traversable and Efficient.

Q.What is output in javascript? 1+2+"3"+4+5

NOTE: This is objective type question, Please click question title for correct answer.

Q.What is TypeScript ?

TypeScript is a programming language from Microsoft that makes it easier to write cross-platform, application scale, JavaScript that runs in any browser or in any host.
TypeScript also supports interfaces, classes (the same syntax as currently proposed by the next version of EcmaScript),  modules, file importing, public and private data, and probably more.

Q.What is Raphael?

Raphael is a small JavaScript library which simplifies drawing the vector graphics easily on the web. Creation of custom chart or cropping of images or rotating the widgets are now very easy with the Raphael library.
It uses the SVG W3C Recommendation and VML as a base for creating graphics.

Q.Give an example of JavaScript Print ?

<input type="button" value="Print this Page" onclick="window.print();">
JavaScript automatically opens a print dialogue box so that users can print the page.

Q.What is a JavaScript Escape Characters ?

In JavaScript, the backslash (\) is an escape character. 

<script type="text/javascript">
<!--
document.write("The "escape" character");
//-->
</script>

As soon as the browser encounters the first double quote, it will think that the string has finished. Further, it will

 result in an 
error because it will be expecting the closing bracket.
<script type="text/javascript">
<!--
document.write("The \"escape\" character");
//-->
</script>

Q.What is Extjs ?

ExtJs is JavaScript application framework that works on all following modern browsers.
IE 6+
Firefox 3.6+ (PC, Mac)
Safari 4+
Chrome 10+
Opera 11+ (PC, Mac
It enables you to develop the best Rich cross-platform applications. It also offers an extraordinary range of UI widgets

 like grids, trees, menus, and more.

Q.Difference between InnerText and InnerHtml ?

The difference between innerText and innerHTML is innerText is interpreted as text where as innerHTML is 
interpreted as HTML.
Example:

<Div ID="Test"> <b>Test for InnerText and InnerHtml</b><Div>
1. document.getElementById('Test').innerHTML // output: <b>Test for InnerText and InnerHtml</b

2. document.getElementById('Test').innerText // output: Test for InnerText and InnerHtml

Q.What is J.W.T ?

JSON Web Token (JWT) is a representing claims (represented as a name/value pair consisting of a Claim Name and a Claim Value) to be transferred between two parties.
Claim in JWT encoded as JSON Object used as the payload of a JSON Web Signature (JWS) structure or as theplaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or MACed and/or encrypted.
 
 

1 comment:

  1. In the answer for appending in an array wouldn't array.push be better than the answer given....

    ReplyDelete

Powered by Blogger.