Saturday, August 16, 2014

Javascript Questions and Answers

JAVASCRIPT  INTERVIEW QUESTIONS :
What is the difference between undefined value and null value?
Undefined value: A value that is not defined and has no keyword is known as undefined value. For example in the declaration, int number; the number has undefined value.
Null value: A value that is explicitly specified by the key word ‘null’ is known as null value. For example in the declaration, String str=null; the str has a null value. The keyword ‘null’ is used here.
Undefined is the value of variable with no value.
Variable can be emptied by setting the value to NULL.
What is this keyword?
It refers to the current object.
What is the difference between == and === ?
The == checks for value equality, but === checks for both type and value.
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.
What is the difference between Client side JavaScript and Server side JavaScript.
Client side java script comprises the basic language and predefined objects which are relevant to running java script in a browser. The client side java script is embedded directly by in the HTML pages. This script is interpreted by the browser at run time.                                                                                                                                                 Client-Side JavaScript (CSJS). It is JavaScript that enables the enables web pages on browsers to run active online content.
Server side java script also resembles like client side java script. It has relevant java script which is to run in a server. The server side java scripts are deployed only after compilation.                                                               Server-Side JavaScript (SSJS) . It is JavaScript that enables back-end access to databases, file systems, and servers.
Difference between SessionState and ViewState
A ViewState is a state of a page within a browser wherein the values of controls persist when post back operation is done. 
When another page is loaded, the previous page data is no longer available.
SessionState is the data of a user session and is maintained on the server side. This data available until user closes the browser or session time-outs.

Methods GET vs. POST in HTML forms.
The GET method in the HTML forms passes the form values by setting the URL.
Eg: If you type the word ‘Hello’ in Google Search, it sets the following URL:
The POST method sends the data to the server without setting the URL:
Eg:
-----------------------------97891525516423
Content-Disposition: form-data; name="username"

Can you explain what isNaN function does?

isNaN function will check an argument and return TRUE (1) if the argument does not seem to be a number.

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

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

Are javascript and jQuery different?

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

How many looping structures can you find in javascript?

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

JavaScript is widely used for ? - client-side web development
Using which tag we insert an JavaScript in HTML page? -  <script></script>
JavaScript is case-sensitive language? – True
We can use the javascript tag within - <head> and<body>

What is the correct syntax for referring to an external script called ” abc.js”? 
<script src=”abc.js”>
What datatypes are supported in Javascript? - Number, String, Undefined, null, Boolean
How do you create a new object in JavaScript?
A function is used for creating custom object classes, by calling it by using the keyword new. A special variable this is references the new object that is being constructed(current object). This function must not return a value. The following code snippet depicts the creation of an object of class myclass.
function myclass() {
this.containedValue = 0;
this.othercontainedValue = 0;
this.anothercontainedValue = 0;
}
var myobject = new myclass();
var myCar = {color:"white",wheels:4,engine:{cylinders:4,size:2.2}}; 
Eg:  Var person = {name:”raj”,age:20}  -  Name is the property and raj is the value.
How to get height and width of different browser in Javascript?
Following examples illustrate the different ways to get height and width of different browser.
For Non-IE
var Width;
var Height;
Width = window.innerWidth;
Height = window.innerHeight;
For IE 6+ in standards compliant mode
Width = document.documentElement.clientWidth;
Height = document.documentElement.clientHeight;
For IE 4 compatible
Width = document.body.clientWidth;
Height = document.body.clientHeight;



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.
How to detect the operating system on the client machine?
The navigator.appVersion string should be used to find the name of the operating system on the client machine. The following code snippet returns the appropriate Operating systems.
<script language="javascript" type="text/javascript">
 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);
 </script>





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.
Where are cookies actually stored on the hard disk? 
The storage of cookies on the hard disk depends on OS and the browser. The Netscape navigator on Windows, the file cookies.txt contains all the cookies. The path is :
c:\Program Files\Netscape\Users\username\cookies.txt
The Internet Explorer stores the cookies on a file by name username@website.txt is
c:\Windows\Cookies\username@Website.txt
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.
What is event bubbling?
Event bubbling describes the behavior of events in child and parent nodes in the Document Object Model (DOM); that is, all child node events are automatically passed to its parent nodes. The benefit of this method is speed, because the code only needs to traverse the DOM tree once. This is useful when you want to place more than one event listener on a DOM element since you can put just one listener on all of the elements, thus code simplicity and reduction. One application of this is the creation of one event listener on a page's body element to respond to any click event that occurs within the page's body.
Explain with an example the use of event handlers in JavaScript.
The events in JavaScript are the actions in a document that result from user activity. The actions are like clicking on a button or typing typing a character in the form. JavaScript object in a document that receives events of different kinds. To handle the events that are taking place requires an even handler that can handle the execution of the events. Event acts like an added attribute that is entered in object’s HTML. The attribute is consisting of event name, sign like (=), instructions. The following code shows the event handler as:
<HTML>
<BODY>
<FORM>
<INPUT TYPE=”button” VALUE=”Hello” onClick=”window.alert (‘HELLO WORLD’)”>
</FORM>
</BODY>
</HTML>
what is an object again?
An object in JavaScript is any unordered collection of key-value pairs. If it’s not a primitive (undefined, null, boolean, number or string) it’s an object.
What is the use of DOM?
DOM is also known as Document Object Model which is used to develop a model with documents or web pages containing objects like elements, links, etc. These objects can be manipulated or certain actions like add, delete or change of an element can be performed using this document object model. Through this change in attributes can be done to get all the list of all the elements in the document. The DOM model responds to API calls that result in documented level of DOM recommendation. It is used to support additional behavior on the web page and use of API give an extensible advent
How to create arrays in JavaScript?
Ans:There are two ways to create array in JavaScript like other languages:
The first way to create array
var names = new Array();
Add Elements in Array:-
names[0] = "Vikas";
names[1] = "Ashish";
names[2] = "Nikhil";
This is the second way:
var names = new Array("Vikas", "Ashish", "Nikhil");
What is the main function of DOM?
- The DOM is known as Document object model and it allows the accessing of the documents like HTML and XML. 
- It allows a platform to be language neutral and provide an interface that allows the dynamic usage of the scripts and programs to access the content.
 
- It also provides a way to update the content, structure and style of the document and a way to represent it in any language.
- It is used with the language and used to create the objects that can be used as a model to allow the interface to be developed with ease.
What is DOM?
DOM is a platform independent, World Wide Web Consortium (W3C) standard form of representation of structured documents as an object-oriented model
What is the Document Object Model, DOM? 
Document Object Model (DOM) is used to query, traverse and manipulate documents like XML or HTML documents. DOM is best suited where the document must be accessed repeatedly or out of sequence order. DOM allows accessing the contents of a web page. It also allows dealing with events that allows capturing and responding to user’s actions. There are different levels of DOM standards depending on the compatibility of the browsers. 
What is the use of DOM in W3C standards?
- HTML DOM is used to add, remove, and change the elements of HTML by using the HTML DOM. 
- DOM considers the entire element in an HTML document as a node and it treats all of them using the same standards.
 
- The document is being given in the document node and all the elements of the HTML are present in the element node.
 
- The text used in the HTML elements is for the text nodes and allows the properties to be used for further use.
 
- HTML usually consists of the attribute and it is stored in the attribute node that allows easy modification of the properties.
What is the purpose of HTML DOM Node Tree?
- HTML DOM view the HTML document with a tree structure format and it consists of root node and child nodes.
- The node-tree is being accessed using the tree formation and the structure in which the elements get created.
 
- The contents that are used being modified or removed using the new elements and it can be created within the limitations.
 
- The structure consists of a document that is the root and within it Root element <html> from where the tree starts.
 
- It consists of sub-elements like <head> and <body> and other text and attributes written in the HTML format.
How does the relationship exist between the node, child and siblings in node-tree?
- Node tree consists of root node, child and siblings with a defined relationship with each other. 
- The relationship is described as such it allows the children on the same level to be called as siblings.
 
- The root node is the top most nodes and through this node the accessing will be done and the elements will be communicated.
 
- Every node in the tree will have exactly one parent node and root doesn’t have any parent in this.
 
- A node at lower down the order can include many other nodes and they will be called as children of parent nodes.



What is DOM?
The DOM is a W3C (World Wide Web Consortium) standard.

The DOM defines a standard for accessing documents like HTML and XML:

"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."

The DOM is separated into 3 different parts / levels:

* Core DOM - standard model for any structured document
* XML DOM - standard model for XML documents
* HTML DOM - standard model for HTML documents

The DOM defines the objects and properties of all document elements, and the methods (interface) to access them.

Explain the difference between a local and a global variable, and how to declare each one.
In JavaScript, global variables can be accessed from anywhere within the program, and are described as having “global scope,” or global visibility within the program. Local variables are temporary variables that only have a scope within the function that generated them, described as having a “local scope.”
// How to declare a local variable
var localVariable = "LocalVariableExample"

// How to declare a global variable
globalVariable = "GlobalVariableExample"
//Undefined

var x;

//Number

var x = 3;

//String

var x = "Example string."

//Boolean

var x = true;
var y = false;

//Object

var newPuppy={
name: "Akira",
haircolor: "golden",
breed: "Shiba Inu",
id: 327
};

//Function

function yourFunctionName()
{
insert code here
}

What is the HTML DOM?
Once a web page loads, your browser generates something called a DOM, or Document Object Model, of the page. The DOM acts as as programming interface for HTML, which defines HTML properties, events, and methods. It also refers to HTML elements as objects.
JavaScript relies on this DOM to alter the elements and attributes of a page, and create the dynamic websites it’s known for. W3Schools.com has a useful image demonstrating the hierarchy of HTML DOM objects:
The official World Wide Web Consortium page for DOM defines it thusly:
The Document Object Model is a platform- and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents.
The document can be further processed and the results of that processing can be incorporated back into the presented page.
This is an overview of DOM-related materials here at W3C and around the web.

Q:           What is JavaScript?
JavaScript is a general-purpose programming language designed to let programmers of all skill levels control the behavior of software objects. The language is used most widely today in Web browsers whose software objects tend to represent a variety of HTML elements in a document and the document itself. But the language can be--and is--used with other kinds of objects in other environments. For example, Adobe Acrobat Forms uses JavaScript as its underlying scripting language to glue together objects that are unique to the forms generated by Adobe Acrobat. Therefore, it is important to distinguish JavaScript, the language, from the objects it can communicate with in any particular environment. When used for Web documents, the scripts go directly inside the HTML documents and are downloaded to the browser with the rest of the HTML tags and content.

JavaScript is a platform-independent,event-driven, interpreted client-side scripting and programming language developed by Netscape Communications Corp. and Sun Microsystems.

Q1.         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.
Q2.         What are JavaScript types?
- Number, String, Boolean, Function, Object, Null, Undefined.
Q3.         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);
Q4.         What does isNaN function do?
- Return true if the argument is not a number.
Q5.         What is negative infinity?
 - It’s a number in JavaScript, derived by dividing negative number by zero.
Q6.         What boolean operators does JavaScript support?
 - &&, || and !
Q7.         What does "1"+2+4 evaluate to?
- Since 1 is a string, everything is a string, so the result is 124.
Q8.         How about 2+5+"8"?
 - Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result.
Q9.         What looping structures are there in JavaScript?
 - for, while, do-while loops, but no foreach.
Q10.       How do you create a new object in JavaScript?
 - var obj = new Object(); or var obj = {};
Q11.       How do you assign object properties?
 - obj["age"] = 17 or obj.age = 17.
Q12.       What’s a way to append a value to an array?
- arr[arr.length] = value;
What is this keyword? - It refers to the current object.

Q13.       How to get value from a textbox?
Write following code
alert(document.getElementById('txtbox1').value);
Q14.       How to get value from dropdown (select) control?
Write following code
alert(document.getElementById('dropdown1').value);
Q15.       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);
            }
        }
Q16.       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.
Q17.       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.
Q18.       What’s the official JavaScript website?
This is a trick question used by interviewers to evaluate the candidate’s knowledge of JavaScript. Most people will simply say javascript.com is the official website.

The truth is- there is no official website for Javascript you can refer to. It was developed by Brendan Eich for Netscape. It was based on the ECMAScript language standard; ECMA-262 being the official JavaScript standard.

Every browser has their own version of JavaScript engine. What one browser supports might not necessarily be supported by the other (very true in case of Internet Explorer). Following are some JavaScript reference pages for popular browsers
·         Mozilla Firefox
·         Microsoft Internet Explorer

Another point to note is that Javascript and java are in no way related to each other than the fact that the trademark for java and javascript lies with Sun Microsystems.
Q19.       Is it possible for you to write a 1-line JavaScript code that concatenates all strings passed into a function?
The following function should help achieve the desired result

function concatenate() {
 return String.prototype.concat.apply('', arguments);
 }
Q20.       How is form submission possible via javascript?

We can achieve the desired form submission by using the function document.forms[0].submit().

It must be noted that the 0 in the piece of code given above refers to the form index. Say we have multiple forms on a particular page. To make all the form procession unique, we give each form index numbers. The first form will have the index number as 0. The second form will have an incremented number, 1. The third will have 2 and so on.
Q21.       List the javascript types?
1.       Number
2.       String
3.       Boolean
4.       Function
5.       Object
6.       Null
7.       Undefined

Q22.       Differentiate between “var a=2” and “a =2”?
The major difference between the two is that one variable is local and the other is global. “var” basically defines the scope of the variable.
When we add var to a variable value assignment, javascript ensures that the variable is confined to whichever function it is assigned to and does not collide with the same name variable within another function.
When we don’t use var, then it is declared as a global function and chances of collision can happen. So it’s always advisable to use “var” before variable value assignment. If needed use an anonymous function for closure.
Q23.       Is it possible to check if a variable is an object?
Yes, it is possible to do so. The following piece of code will help achieve the same.
if(abc && typeof abc === "object") {
 console.log('abc is an object and does not return null value');
 }
Q24.        Can you explain what isNaN function does?
isNaN function will check an argument and return TRUE (1) if the argument does not seem to be a number.
Q25.       How many looping structures can you find in javascript?
If you are a programmer, you know the use of loops. It is used to run a piece of code multiple times according to some particular condition. Javascript being a popular scripting language supports the following loops
v  for
v  while
v  do-while loop

There is no ForEach loop in javascript. You can implement it though using this hack.

Q26.       Are javascript and jQuery different?
jQuery is a quick as well as concise JavaScript Library that simplifies HTML document traversing, animating, event handling, & Ajax interactions for the purpose of quick web development needs. So although they are not entirely different, both are not the same either!
Q27.       Explain the strict mode in Javascript.
The strict mode ensures that if functions are not properly thought it, those are disabled. It also kept a check on potentially unsafe actions and throw errors when it happens.
Chances of you needing to explain more during javascript interview is high. So you can refer this article for detailed information on usage of strict mode.
Q28.       What is the difference between “==” and “===”?
While “==” checks only for equality, “===” checks for equality as well as the type.
Q29. Explain javascript closures?
A basic overview of javascript closures is that it is a stack-frame which is not de-allocated when the function returns.
This is a pretty difficult to understand concept in javascript for beginners. So read this article to understand in-depth about javascript closures.

Q30. How to add Buttons in JavaScript?
The most basic and ancient use of buttons are the "submit" and "clear", which appear slightly before the Pleistocene period. Notice when the "GO!" button is pressed it submits itself to itself and appends the name in the URL.
<form action="" name="buttonsGalore" method="get">
Your Name: <input type="text" name="mytext" />


<input type="submit" value="GO!" />
<input type="reset" value="Clear All" />
</form>

Another useful approach is to set the "type" to "button" and use the "onclick" event.
<script type="text/javascript">
function displayHero(button) {
alert("Your hero is \""+button.value+"\".");
}
</script>

<form action="" name="buttonsGalore" method="get">
<fieldset style="margin: 1em; text-align: center;">
<legend>Select a Hero</legend>
<input type="button" value="Agamemnon" onclick="displayHero(this)" />
<input type="button" value="Achilles" onclick="displayHero(this)" />
<input type="button" value="Hector" onclick="displayHero(this)" />
<div style="height: 1em;" />
</fieldset>
</form>

Q31.       What can javascript programs do?
Generation of HTML pages on-the-fly without accessing the Web server. The user can be given control over the browser like User input validation Simple computations can be performed on the client's machine The user's browser, OS, screen size, etc. can be detected Date and Time Handling

Q32. How to set a HTML document's background color?
document.bgcolor property can be set to any appropriate color

Q33.  What does isNaN function do?
Return true if the argument is not a number.

Q 34. What is negative infinity?
It’s a number in JavaScript, derived by dividing negative number by zero.

Q35.       In a pop-up browser window, how do you refer to the main browser window that opened it?
Use window.opener to refer to the main window from pop-ups.

Q36.       What is the data type of variables of in JavaScript?
All variables are of object type in JavaScript.

Q37.       Methods GET and POST in HTML forms - what's the difference?
GET: Parameters are passed in the querystring. Maximum amount of data that can be sent via the GET method is limited to about 2kb.
POST: Parameters are passed in the request body. 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.

Q 38. How to write a script for "Select" lists using javascript?
1. To remove an item from a list set it to null
mySelectObject.options[3] = null;
2. To truncate a list set its length to the maximum size you desire
mySelectObject.length = 2;
3. To delete all options in a select object set the length to 0.
mySelectObject.leng

Q 39. Text From Your Clipboard?
It is true, text you last copied for pasting (copy & paste) can be stolen when you visit web sites using a combination of JavaScript and ASP (or PHP, or CGI) to write your possible sensitive data to a database on another server.

Q 40. What does the "Access is Denied" IE error mean?
The "Access Denied" error in any browser is due to the following reason.
A javascript in one window or frame is tries to access another window or frame whose document's domain is different from the document containing the script.

Q 41. Is a javascript script faster than an ASP script?
Yes.Since javascript is a client-side script it does require the web server's help for its
computation,so it is always faster than any server-side script like ASP,PHP,etc..

Q 42. Are Java and JavaScript the Same?
No.java and javascript are two different languages.
Java is a powerful object - oriented programming language like C++,C whereas Javascript is a client-side scripting language with some limitations.

Q 43. How to embed javascript in a web page?
javascript code can be embedded in a web page between <script langugage="javascript"></script> tags

Q 44. What Boolean operators does JavaScript support?
&&, || and !

Q45. What does "1"+2+4 evaluate to?
Since 1 is a string, everything is a string, so the result is 124.

Q46. How is JavaScript different from Java?

 JavaScript was developed by Brendan Eich of Netscape; Java was developed at Sun Microsystems. While the two languages share some common syntax, they were developed independently of each other and for different audiences. Java is a full-fledged programming language tailored for network computing; it includes hundreds of its own objects, including objects for creating user interfaces that appear in Java applets (in Web browsers) or standalone Java applications. In contrast, JavaScript relies on whatever environment it's operating in for the user interface, such as a Web document's form elements.
 JavaScript was initially called LiveScript at Netscape while it was under development. A licensing deal between Netscape and Sun at the last minute let Netscape plug the "Java" name into the name of its scripting language. Programmers use entirely different tools for Java and JavaScript. It is also not uncommon for a programmer of one language to be ignorant of the other. The two languages don't rely on each other and are intended for different purposes. In some ways, the "Java" name on JavaScript has confused the world's understanding of the differences between the two. On the other hand, JavaScript is much easier to learn than Java and can offer a gentle introduction for newcomers who want to graduate to Java and the kinds of applications you can develop with it.



Q47.  What’s a way to append a value to an array?
arr[arr.length] = value;

Q48.  How do you assign object properties?
obj["age"] = 17 or obj.age = 17.

Q 49. How do you create a new object in JavaScript?
var obj = new Object(); or var obj = {};

Q 50. What looping structures are there in JavaScript?
for, while, do-while loops, but no foreach.

Q51. How about 2+5+"8"?
Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result.

Q52. What does "1"+2+4 evaluate to?
Since 1 is a string, everything is a string, so the result is 124.
Q53.  What boolean operators does JavaScript support?
&&, || and !
Q54. What is negative infinity?
It’s a number in JavaScript, derived by dividing negative number by zero.

Q55.  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);
What does isNaN function do? - Return true if the argument is not a number.
Q56. What are JavaScript types?
Number, String, Boolean, Function, Object, Null, Undefined.
Q57. 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
Q58. What does break and continue statements do?
Continue statement continues the current loop (if label not specified) in a new iteration whereas break statement exits the current loop.
Q59. 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.
Q60. What is === operator ?
==== is strict equality operator ,it returns true only when the two operands are having the same value without any type conversion.
Q61.  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.
Q62.  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.
Q63. 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
Q63. What is the difference between undefined value and null value?
v  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.
v  Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.
v  Unassigned variables are initialized by JavaScript with a default value of undefined. JavaScript never sets a value to null. That must be done programmatically.
Q64. What does undefined value mean in javascript?
Undefined value means the variable used in the code doesnt exist or is not assigned any value or the property doesnt exist.

Q65. To put a “close window” link on a page ?
 <a href=’javascript:window.close()’ class=’mainnav’> Close </a>

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

Q67. How to comment javascript code?
 Use // for line comments and
 /*

*/ for block comments

Q68. Name the numeric constants representing max,min values
 Number.MAX_VALUE
 Number.MIN_VALUE

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

Q70. How do you create a new object in JavaScript?
 var obj = new Object(); or var obj = {};

Q71. How do you assign object properties?
 obj["age"] = 17 or obj.age = 17.

Q72. What’s a way to append a value to an array?
 arr[arr.length] = value;

Q73. What is this keyword?
 It refers to the current object.



Q74. How to find the selected radio button immediately using the ‘this’ variable?
<script>
 function favAnimal(button) {
 alert(‘You like ‘+button.value+’s.’);
 }
 </script>
 <input type=”radio” name=”marsupial” value=”kangaroo”
 onchange=”favAnimal(this)”>Kangaroo
 <br /><input type=”radio” name=”marsupial” value=”Opossum”
 onchange=”favAnimal(this)”>Opossum
 <br /><input type=”radio” name=”marsupial” value=”Tasmanian Tiger”
 onchange=”favAnimal(this)”>Tasmanian Tiger

Q75. How to find radio button selection when a form is submitted?
 <script type=”text/javascript”>
 function findButton() {
 var myForm = document.forms.animalForm;
 var i;
 for(i=0;i<myForm.marsupial.length; i++) {
 if(myForm.marsupial[i].checked) {
 break;
 }
 }
 alert(“You selected \”"+myForm.marsupial[i].value+“\”.”);
 }
 </script>
 <form name=”animalForm” action=”">
 <input type=”radio” name=”marsupial” value=”kangaroo” />Kangaroo
 <br /><input type=”radio” name=”marsupial” value=”Opossum” />Opossum
 <br /><input type=”radio” name=”marsupial” value=”Tasmanian Tiger” />Tasmanian Tiger

<input type=”button” name=”GO” value=”GO” onclick=”findButton()” />

Q76. How to disable an HTML object ?
 document.getElementById(“myObject”).disabled = true;

Q77. To write messages to the screen without using “document.write()” ?
 Changing the contents of an element is a much better solution. When the method showStatus is invoked it will change the content of the span.
 …
 function showStatus(message) {
 var element = document.getElementById(“mystatus”);
 element.textContent = message; //for Firefox
 element.innerHTML = message; //for IE (why can’t we all just get along?)
 return true;
 }
 …
 <span id=”mystatus”>Test. </span>
 …

Q78. How to Add new elements dynamically ?
 <html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>
 <head>
 <title>t1</title>
 <script type=”text/javascript”>
 function addNode() {
 var newP = document.createElement(“p”);
 var textNode = document.createTextNode(” I’m a new text node”);
 newP.appendChild(textNode);
 document.getElementById(“firstP”).appendChild(newP);
 }
 </script>
 </head>

<body onload=”addNode();” style=” background: url(‘../images/Sand-1280.jpg’); background-color: yellow;”>

<p id=”firstP”>firstP<p>

</body>
 </html>

Q79. How to have an element invoke a javascript on selection, instead of going to a new URL: ?
 <script type=”text/javascript”>
 function pseudoHitMe() {
 alert(“Ouch!”);
 }
 </script>
 <a href=”javascript:pseudoHitMe()“>hit me</a>

Q80. How to have the status line update when the mouse goes over a link (The support of the status line is sporadic)?
 <a href=”javascript.shtml”
 onmouseover=”window.status=’Hi There!’;return true”
 onmouseout=”window.status=”;return true”>Look at the Status bar</a>
 Look at the Status bar as your cursor goes over the link.



Q81. How to create a popup warning box
alert(‘Warning: Please enter an integer between 0 and 100.’);

Q82. How to create a confirmation box?
 confirm(“Do you really want to launch the missile?”);

How to create an input box?
 prompt(“What is your temperature?”);

Q83. How to setting a cookie with the contents of a textbox ?
 Values stored in cookies may not have semicolons, commas, or spaces. You should use the handy “escape()” function to encode the values, and “unescape()” to retrieve them.

//Sets cookie of current value for myTextBox
 function TextBoxOnchange() {
 var myBox = window.document.getElementById(myTextBox”);
 document.cookie = “myTextBox=”+ escape(myBox.value) + getExpirationString();
 }
//return a string like “;expires=Thu, 5 Jan 2006 16:07:52 UTC”
 function getExpirationString() {
 var exp = new Date();
 var threemonths = exp.getTime()+(120*24*60*60*1000);
 exp.setTime(threemonths);
 return “;expires=”+exp.toGMTString();
 }

This is called from the event handler in the HTML.

<input name=”myTextBox” type=”text” id=”myTextBox”
 onchange=”javascript:TextBoxOnchange()” />

Q84. How to getting values from cookies to set widgets?
 function getCookieData(labelName) {
 //from Danny Goodman
 var labelLen = labelName.length;
 // read cookie property only once for speed
 var cookieData = document.cookie;
 var cLen = cookieData.length;
 var i = 0;
 var cEnd;
 while (i < cLen) {
 var j = i + labelLen;
 if (cookieData.substring(i,j) == labelName) {
 cEnd = cookieData.indexOf(“;”,j);
 if (cEnd == -1) {
 cEnd = cookieData.length;
 }
 return unescape(cookieData.substring(j+1, cEnd));
 }
 i++;
 }
 return “”;
 }

//init() is called from the body tag onload function.
 function init() {
 setValueFromCookie(“brand”);
 setValueFromCookie(“market”);
 setValueFromCookie(“measure”);
 }

function setValueFromCookie(widget) {
 if( getCookieData(widget) != “”) {
 document.getElementById(widget).value = getCookieData(widget);
 }
 }

//if you name your cookies the widget ID, you can use the following helper function
 function setCookie(widget) {
 document.cookie = widget + “=” +
 escape(document.getElementById(widget).value) + getExpirationString();
 }

Q85. How to change style on an element?
 Between CSS and javascript is a weird symmetry. CSS style rules are layed on top of the DOM. The CSS property names like “font-weight” are transliterated into “myElement.style.fontWeight”. The class of an element can be swapped out. For example:
 document.getElementById(“myText”).style.color = “green”;
 document.getElementById(“myText”).style.fontSize = “20;
 -or-
 document.getElementById(“myText”).className = “regular”;





Q86. How to Handle Event Handlers?
You can add an event handler in the HTML definition of the element like this,
 <script type=”text/javascript”><!–
 function hitme() {
 alert(“I’ve been hit!”);
 }
 // –>
 </script>
 <input type=”button” id=”hitme” name=”hitme” value=”hit me” onclick=”hitme()”

Or, interestingly enough you can just assign the event’s name on the object directly with a reference to the method you want to assign.

<input type=”button” id=”hitme2 name=”hitme2 value=”hit me2/>
 <script type=”text/javascript”><!–
 function hitme2() {
 alert(“I’ve been hit too!”);
 }
 document.getElementById(“hitme2).onclick = hitme2;
 // –>
 </script>

You can also use an anonymous method like this:

document.getElementById(“hitme3).onclick = function () { alert(“howdy!”); }

You can also use the W3C addEvventListener() method, but it does not work in IE yet:

<input type=”button” id=”hitme4 name=”hitme4 value=”hit me4/>
 <script type=”text/javascript”><!–
 function hitme4() {
 alert(“I’ve been hit four!”);
 }
 if(document.getElementById(“hitme4).addEventListener) {
 document.getElementById(“hitme4).addEventListener(“click”, hitme4, false);
 }
 // –>
 </script>

Q87. How to remove the event listener: ?
 <script type=”text/javascript”><!–
 document.getElementById(“hitme4).removeEventListener(“click”, hitme4, false);
 // –>
 </script>

Key Events

“onkeydown”, “onkeypress”, “onkeyup” events are supported both in ie and standards-based browsers.

<script type=”text/javascript”>
 function setStatus(name,evt) {
 evt = (evt) ? evt : ((event) ? event : null); /* ie or standard? */
 var charCode = evt.charCode;
 var status = document.getElementById(“keyteststatus”);
 var text = name +”: “+evt.keyCode;
 status.innerHTML = text;
 status.textContent = text;
 }
 </script>
 <form action=”">
 <input type=”text” name=”keytest” size=”1 value=”"
 onkeyup=”setStatus(‘keyup’,event)”
 onkeydown=”setStatus(‘keydown’,event)”
 />
 <p id=”keyteststatus”>status</p>
 </form>

Q88. How to make elements invisible ?
 Change the “visibility” attribute of the style object associated with your element. Remember that a hidden element still takes up space, use “display” to make the space disappear as well.

if ( x == y) {
 myElement.style.visibility = ‘visible’;
 } else {
 myElement.style.visibility = ‘hidden’;
 }

Q89. How to set the cursor to wait ?
 In theory, we should cache the current state of the cursor and then put it back to its original state.
 document.body.style.cursor = ‘wait’;
 //do something interesting and time consuming
 document.body.style.cursor = ‘auto’;

Q90. How to reload the current page ?
 window.location.reload(true);

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

Q92.  What is the difference between == and === ?
The == checks for value equality, but === checks for both type and value.

Q93. How do style= you change the style/class on any element?
document.getElementById(“myText”).style.fontSize = “20;
 -or-
 document.getElementById(“myText”).className = “anyclass”;
Q94. 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
Q95. 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.
Q96. 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
Q97. How to create arrays in JavaScript?
We can declare an array like this
 var scripts = new Array();
 We can add elements to this array like this
 scripts[0] = “PHP”;
 scripts[1] = “ASP”;
 scripts[2] = “JavaScript”;
 scripts[3] = “HTML”;
 Now our array scrips has 4 elements inside it and we can print oraccess them by using their index number. Note that index number startsfrom 0. To get the third element of the array we have to use the indexnumber 2 . Here is the way to get the third element of an array.
 document.write(scripts[2]);
 We also can create an array like this
 var no_array = new Array(21, 22, 23, 24, 25);
Q98.  What does isNaN function do?
This function returns true if the value is NaN(Not a Number), and false if not.


Q99. What are the built-in objects in JavaScript?
 String, Date, Array, Boolean, and Math.


Q100. What are the different ways to create objects in JavaScript?
By invoking the built-in constructor.

var personObj1 = new Object(); // empty object with no properties and methods.
personObj1.name = "John"  ;     //add a property
personObj1.status = "Active";     //add a property
//add a method by associating a function to variable isActive variable.
personObj1.isActive = function() {
     return this.status;



By creating a constructor (i.e. a template), and creating an object from the constructor. The Person constructor is like any other function, and it is a convention to start the function name with an uppercase letter to differentiate it with other functions.

                function Person(name, status) {
    this.name = name;
    this.status = status;
    //add a method by associating a function to variable isActive variable.
    personObj1.isActive = function() {
       return this.status;
    }  
   
}

var personObj1 = new Person("John", "Active");


Creating the object as a Hash Literal. This is what used by the JSON, which is a subset of the object literal syntax.

var personObj1 = { };    // empty object

var personObj2 = {

   name: "John",
   status: "Active",
   isActive: function() {
       return this.status;
   

};


Q101. Does JavaScript has a built-in concept of inheritance?
It does to some extent. You can think of every object as inheriting from it's "prototype".

Q102. What is a "prototype" property?
A prototype is a built-in property of every JavaScript object. For example,
var personObj1 = new Object();  // empty object with no properties and methods.
personObj1.name = "John"  ;     //add a property
personObj1.status = "Active";   //add a property

 Now, if you create another person object as shown below, all the properties will be empty, and needs to be reassigned.
var personObj2 = new Object();  // empty object with no properties and methods.
personObj2.name = "John"  ;     //add a property
personObj2.status = "Active";   //add a property

 What if you want to set all the Person object status to be "Active" by default without having to explicitly assign it every time? This is where the "prototype" property comes in handy as shown below.
var personObj1 = new Object();            //empty object with no properties and methods.
personObj1.name = "John"  ;               //add a property
personObj1.prototype.status = "Active";   //add a prototype property that will set "Active" as the default
 var personObj2 = new Object();  // empty object with status="Active" will be created.
personObj2.name = "John"  ;     // add a property

 When you create an object via a constructor as in var personObj1 = new Person("John", "Active"), the prototype property is also set. When you actually create an object via a constructor, the new operator actually performs the following tasks.

STEP 1: Creates an empty object as in var personObj1 = new Object();

STEP 2: Attach all properties and methods of the prototype of the function to the resulting object.

STEP 3: Invoke the function "Person" by passing the new object as the "this" reference.


 It is important to understand that, all the objects that are created via a constructor function will have the same prototype. This means, if you modify any one object that has been created via the constructor, you will be modifying all the objects that have been created and the new ones you will be creating via the constructor function. You can think of this as every object is inheriting from it's prototype. So, the above approach of individually adding to some properties as in

personObj1.prototype.status = "Active";


 can be very handy for methods and constants, and this "prototype" approach is used by many JavaScript frameworks.

Q103. What are some of the best practices relating to coding with JavaScript?
Use proven frameworks like jQuery, EXT JS, etc to ensure cross browser compatibility, and quality code.
Provide a clean separation of content, CSS, and JavaScript. This means store all Javascript code in external script files and build pages that do not rely on Javascript to be usable.
Instead of:
<input id="btn1" type="button" value="click-me1" onclick="test()"/>
Use:
<input id="btn1" type="button" class="something" value="click-me1" /> 
 The above page snippet does not depend on the JavaScript function. The JQuery function below

$('input.something').click(function(){
    //do something here
    alert('The button is clicked');
});

 jQuery allows you to easily attach a click event to the result(s) of your selector. So the code will select all of the <input /> tags of class “something” and attach a click event that will call the function.
 Also instead of
if(someCondition)
    document.write("write something ........... ");
 Use:
                <div title="something"> ... </div>

var titleElement = $('div[title="something"]');
titleElement.text('Better Approach');
 The above page is renedred as 100% (X)HTML without requiring the JavaScript to write something.
Use code quality tools like JSLint.
Use unit testing frameworks like Jasmine, qUnit, etc.
Use "===" instead of "==". If two operands are of the same type and value, then === produces true and !== produces false. If you use "==" or !="" you may run into issues if the operands are of different types.
Avoid using the eval(…) function as it poses a security risk and can also adversely affect performance as it accesses the JavaScript compiler.
Namespaces are essential for avoiding type name collisions. JavaScript does not have packages as in Java. But in JavaScript, this can be simulated with empty objects. For example

var MyPage1 = { };   // empty object acting as a namespace

MyPage1.Person = function(name, status) {
    this.name = name;
    this.status = status;
}

MyPage1.Person.protoyype  =

{
    isActive: function() {
         return this.status;
    }

}
 var personObj1 = new MyPage1.Person("John", "Active");
console.log(personObj1.isActive());

Simulate encapsulation with Douglas Crawford's approach as shown below as JavaScript does not have access modifiers like private, protected, etc as in Java.
                function Person(name, status) {
      this.get_name = function( ) { return name; }
      this.get_status = function( ) {return status; }
}

Person.prototype.isActive = function( )
{
      return this.get_status();
}


var personObj1 = new Person("John","Active");
console.log(personObj1.isActive( )) ;

                 

Favor the JavaScript literal way with { … } as opposed to the new Object() to create new objects as the literal way is much more robust and also makes it simpler to code and read.
                 

Favor [ ] to declare an array as opposed to an array object with new Array( ). For example,
var vehicles = ['Car', 'Bus'] ; // creates an array  
var vehicles = new Array( ); // creates an array object
vehicles[0] = ''Car" ;
vehicles[1] = 'Bus' ;
Favor using semicolons (;), and use comma separated variables as opposed to repeating vars. For example

 //okay
var x = 5;
var y = 6;
var z = 9;
var x =5, y=6,z = 9; // better
Use console.log(...) as oppose to alert(...); for debugging.
Q104.  What is a callback function? Why would you need callback functions?
 As mentioned earlier, the functions in JavaScript are actually objects. For example,
var functionAdd = new Function("arg1", "arg2", "return arg1 * arg2;");
functionAdd(5,9);  // returns 14
functionAdd(2,3);  // returns 5


 So, the functions can be passed as arguments to other functions and invoked from other functions. For example,
function functionAdd(arg1, arg2, callback) {
  var result = arg1 + arg2
  // Since we're done, let's call the callback function and pass the result
  callback(result);
}


// call the function
functionAdd(5, 15, function(result) {
    // this anonymous function will run when the callback is called
 console.log("callback called! " + result);
});



Q105. What are the different ways to invoke a function? What would the implicit reference "this" refer tonbsp; ?
The functions can be invoked via one of the following 5 ways

function_name(param1, param2, etc); --> "this" refers to global object like window.
obj1.function_name(param1,param2,etc);  --> "this" refers to obj1.
The constructor.
function_name.call(objRef, param1);    //remember that the functions in JavaScript is like an object and it has it's own methods like toString(..), call(.div class=..), apply(...), etc.
function_name.apply(objRef, params[parama1,param2, etc]);

 So, why use  function_name.call(...) or function_name.apply( ... ) as opposed to just function_name( ... )? Let's look at this with some examples.
var x = 1;           //global variable x;

var obj1 = {x:3};   //obj1 variable x
var obj2 = {x:9};   //obj2 variable x

function function_name(message) {
   alert(message + this.x) ;
}


function_name("The <span id="IL_AD3" class="IL_AD">number</span> is ");              //alerts the global x --> The number is 1

//the first argument is the obj reference on which to invoke the function, and the
//the second argument is the argument to the function call
function_name.call(obj1, "The number is ");   //alerts the obj1's x --> The number is 3
function_name.call(obj2, "The number is ");   //alerts the obj2's x --> The number is 5



//the first argument is the obj reference on which to invoke the function, and the
//the second argument is the argument to the function call as an array
function_name.apply(obj1, ["The number is "]);   //alerts the obj1's x --> The number is 3
function_name.apply(obj2, ["The number is "]);   //alerts the obj2's x --> The number is 5


 The purpose is of call and apply methods are  to invoke the function for any object without being bound to an instance of the this object. In the above example, the this object is the global object with the x value of 1.   In a function called directly without an explicit owner object, like function_name(), causes the value of this to be the default object (window in the browser). The call and apply methods allow you to pass your own object to be used as the "this" reference. In the above example, the obj1 and obj2 were used as "this" reference.


No comments:

Post a Comment