JavaScript

1. What is JavaScript?
JavaScript is a platform-independent, event-driven, interpreted client-side scripting and programming language developed by Netscape Communications Corp. and Sun Microsystems.
2. How is JavaScript different from Java?
Java is an entire programming language developed by Sun Microsystems, while JavaScript is a scripting language that was introduced by Netscape.
3.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.
4.How do you submit a form using Javascript?
Use document.forms[0].submit();
(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).
5.How do we get JavaScript onto a web page?
JavaScript can be placed inside of the <head> element or it can directly add inside <body> element.
<script type=”text/javascript” >
// Add scripting code here
</script>
JavaScript can be referenced from a separate file also
<script type=”text/javascript” SRC=”myStuff.js”></script>
6.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. However , this can be done by coding a Java applet that reads files for the script.
7.How to detect the operating system on the client machine?
In order to detect the operating system on the client machine, the navigator.appVersion
string (property) should be used.
8.How can JavaScript make a Web site easier to use? That is, are there certain JavaScript techniques that make it easier for people to use a Web site?
JavaScript’s greatest potential gift to a Web site is that scripts can make the page more immediately interactive, that is, interactive without having to submit every little thing to the server for a server program to re-render the page and send it back to the client. For example, consider a top-level navigation panel that has, say, six primary image map links into subsections of the Web site. With only a little bit of scripting, each map area can be instructed to pop up a more detailed list of links to the contents within a subsection whenever the user rolls the cursor atop a map area.
9.What are JavaScript types?
Number, String, Boolean, Function, Object, Null, Undefined.
10.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); 
11.How to create arrays in JavaScript?
var arr = new Array();
arr[0] = ‘HTML’
arr[1] = ‘JavaScript’
// We also can create the arrays like this
var arr = new Array(21, 22, 23, 24, 25);
12.How do you target a specific frame from a hyperlink?
Include the name of the frame in the target attribute of the hyperlink. <a href=”mypage.htm” target=”myframe”>>My Page</a>
13.What is a fixed-width table and its advantages?
Fixed width tables are rendered by the browser based on the widths of the columns in the first row, resulting in a faster display in case of large tables. Use the CSS style table-layout:fixed to specify a fixed width table.
If the table is not specified to be of fixed width, the browser has to wait till all data is downloaded and then infer the best width for each of the columns. This process can be very slow for large tables.
14.Example of using Regular Expressions for syntax checking in JavaScript
var re = new RegExp(“^(&[A-Za-z_0-9]{1,}=[A-Za-z_0-9]{1,})*$”);
var text = myWidget.value;
var OK = re.test(text);
if( ! OK ) {
alert(“The extra parameters need some work.\r\n Should be something like: \”&a=1&c=4\””);
}
15.How to add Buttons in JavaScript?
<input type=”submit” value=”GO!” />
Another useful approach is to set the “type” to “button” and use the “onclick” event.
<input type=”button” value=”Hector” onclick=”displayHero(this)” />
16.Where are cookies actually stored on the hard disk?
This depends on the user’s browser and OS.
In the case of Netscape with Windows OS,all the cookies are stored in a single file called
cookies.txt
c:\Program Files\Netscape\Users\username\cookies.txt
In the case of IE,each cookie is stored in a separate file namely username@website.txt.
c:\Windows\Cookies\username@Website.txt
17.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
18.How to set a HTML document’s background color?
document.bgcolor property can be set to any appropriate color.
19.How can JavaScript be used to personalize or tailor a Web site to fit individual users?
JavaScript-enhanced page can instruct the browser to render only certain content based on the browser, operating system, and even the screen size.
Scripting can even go further if the page author desires. For example, the author may include a preference screen that lets the user determine the desired background and text color combination. A script can save this information on the client in a well-regulated local file called a cookie. The next time the user comes to the site, scripts in its pages look to the cookie info and render the page in the color combination selected previously. The server is none the wiser, nor does it have to store any visitor-specific information.
20.What does isNaN function do?
Return true if the argument is not a number. 
21.What is negative infinity?
It’s a number in JavaScript, derived by dividing negative number by zero.
22.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.
23.What is the data type of variables of in JavaScript?
All variables are of object type in JavaScript.
24.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.
25.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
26.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.
27.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.
28.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..
29.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.
30.How to embed javascript in a web page?
javascript code can be embedded in a web page between <script
langugage=”javascript”></script> tags 
31.What boolean operators does JavaScript support?
&&, || and !
32.What does “1”+2+4 evaluate to?
Since 1 is a string, everything is a string, so the result is 124. 
33.How to get the contents of an input box using Javascript?
Use the “value” property.
var myValue = window.document.getElementById(“MyTextBox”).value;
34.How to determine the state of a checkbox using Javascript?
var checkedP = window.document.getElementById(“myCheckBox”).checked;
35.How to set the focus in an element using Javascript?
document.forms[0].elements[“myelementname”].focus(); 
36.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=”abc.js”></script>
37.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. 
38.What is a prompt box?
A prompt box allows the user to enter input by providing a text box.
39.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”);
40.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.
41.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.
42.How to Accessing Elements using javascript?
We can use the “getElementById” method (which is generally preferred)
document.getElementById(“useless”).style.color = “red”;
43.What looping structures are there in JavaScript?
for, while, do-while loops, but no foreach.
44.To put a “close window” link on a page ?
<a href=’javascript:window.close()’ class=’mainnav’> Close </a>
45.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
46.How to comment javascript code?
Use // for line comments and
/* */ for block comments
47.Name the numeric constants representing max,min values
Number.MAX_VALUE
Number.MIN_VALUE
48.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.
49.How do you create a new object in JavaScript?
var obj = new Object(); or var obj = {};
50.How do you assign object properties?
obj[“age”] = 17 or obj.age = 17.
51.What’s a way to append a value to an array?
arr[arr.length] = value;
52.What is this keyword?
It refers to the current object.
53.What does the term sticky session mean in a web-farm scenario? Why would you use a sticky session? What is the potential disadvantage of using a sticky session?
Sticky session refers to the feature of many commercial load balancing solutions for web-farms to route the requests for a particular session to the same physical machine that serviced the first request for that session. This is mainly used to ensure that a in-proc session is not lost as a result of requests for a session being routed to different servers. Since requests for a user are always routed to the same machine that first served the request for that session, sticky sessions can cause uneven load distribution across servers.
54.To set all checkboxes to true using JavaScript?
var checkboxes = document.getElementsByTagName(“input”);
checkboxes.item(0).checked = true;
55.How to select an element by id and swapping an image ?
..
<script language=”JavaScript” type=”text/javascript” >
function setBeerIcon() {

var beerIcon = document.getElementById(“beerIcon”);
beerIcon.src = “images/”+getSelectValue(“beer”)+”.jpg”;
}
</script>

<img border=”0″ src=”” id=”brandIcon” alt=”brand” />

<select name=”beer” id=”beer” onChange=”setButton();setBeerIcon();”>
<option value=”–Select–“>Select beer</option>
<option value=”heineken”>heineken</option>
<option value=”sol”>sol</option>
<option value=”amstellight”>amstellight</option>
<option value=”coronalight”>coronalight</option>
<option value=”coronaextra”>coronaextra</option>
<option value=””></option>
</select>
56.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.
57.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
58.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
59.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.
60.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.
61.What is === operator ?
==== is strict equality operator ,it returns true only when the two operands are having the same value without any type conversion.
62.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
63.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()” />
64.How to disable an HTML object
document.getElementById(“myObject”).disabled = true;
65.To write messages to the screen without using “document.write()” ?

<span id=”mystatus”>Test. </span>

var element = document.getElementById(“mystatus”);
element.textContent = message; //for Firefox
element.innerHTML = message; //for IE
66.How to Add new elements dynamically.

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

var newP = document.createElement(“p”);
var textNode = document.createTextNode(” I’m a new text node”);
newP.appendChild(textNode);
document.getElementById(“firstP”).appendChild(newP);
67.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>
68.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.
69.How to create a popup warning box
alert(‘Warning: Please enter an integer between 0 and 100.’);
70.How to create a confirmation box?
confirm(“Do you really want to launch the missile?”);
71.How to create an input box?
prompt(“What is your temperature?”);
72.How to open a window with no toolbar, but with the location object.
window.open(“http://www.mysite.org/Misc/Pennies”,”Pennies”,”resizable=yes, status=yes,toolbar=yes,location=yes,menubar=yes,scrollbars=yes,width=800,height=400″);
73.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.

<input name=”myTextBox” type=”text” id=”myTextBox”/>

var myBox = window.document.getElementById(myTextBox”);
document.cookie = “myTextBox=”+ escape(myBox.value);
74.How to getting values from cookies to set widgets?
….
var cookieData = document.cookie;
var cEnd = cookieData.length;
unescape(cookieData.substring(0, cEnd));

75.How to Handle Event Handlers?

function onHit() {
alert(“I’ve been hit!”);
}

<input type=”button” id=”hitme” name=”hitme” value=”hit me” onclick=”onHit()” />
Or
document.getElementById(“hitme”).onclick = onHit;
Or
document.getElementById(“hitme”).onclick = function () { alert(“howdy!”); }
Or
document.getElementById(“hitme”).addEventListener(“click”, onHit, false); 
76.How to remove the event listener:
document.getElementById(“hitme”).removeEventListener(“click”, onHit, false);
77.How to change style on an element?
document.getElementById(“myText”).style.color = “green”;
document.getElementById(“myText”).style.fontSize = “20”;
-or-
document.getElementById(“myText”).className = “regular”;
78.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’;
}
79.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’; 
80.How to reload the current page
window.location.reload(true); 
81.how to force a page to go to another page using JavaScript?
<script language=”JavaScript” type=”text/javascript” ><!– location.href=”http://newhost/newpath/newfile.html”; //–></script>
82.How to convert a string to a number using JavaScript?
You can use the parseInt() and parseFloat() methods. Notice that extra letters following a valid number are ignored, which is kinda wierd but convenient at times.
parseInt(“100”) ==> 100
parseFloat(“98.6”) ==> 98.6
parseFloat(“98.6 is a common temperature.”) ==> 98.6
parseInt(“aa”) ==> Nan //Not a Number
parseInt(“aa”,16) ==> 170 //you can supply a radix or base
83.How to convert numbers to strings using JavaScript?
You can prepend the number with an empty string
var mystring = “”+myinteger;
or
var mystring = myinteger.toString();
You can specify a base for the conversion,
var myinteger = 14;
var mystring = myinteger.toString(16);

mystring will be “e”.
84.How to test for bad numbers using JavaScript?
the global method, “isNaN()” can tell if a number has gone bad.
var temperature = parseFloat(myTemperatureWidget.value);
if(!isNaN(temperature)) {
alert(“Please enter a valid temperature.”);
}
85.What’s Math Constants and Functions using JavaScript?
The Math object contains useful constants such as Math.PI, Math.E
Math also has a zillion helpful functions.
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 
86.What’s the Date object using JavaScript?
Time inside a date object is stored as milliseconds since Jan 1, 1970.
new Date(06,01,02) // produces “Fri Feb 02 1906 00:00:00 GMT-0600 (Central Standard Time)”
new Date(06,01,02).toLocaleString() // produces “Friday, February 02, 1906 00:00:00”
new Date(06,01,02) – new Date(06,01,01) // produces “86400000” 
87.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.
88.How to delete an entry using JavaScript?
The “delete” operator removes an array element, but oddly does not change the size of the array.
89.How to use strings as array indexes using JavaScript?
Javascript does not have a true hashtable object, but through its wierdness, you can use the array as a hashtable.

<script type=”text/javascript”>
var days = [“Sunday”,”Monday”,”Tuesday”,”Wednesday”, “Thursday”,”Friday”,”Saturday”];

for(var i=0; i < days.length; i++) {
days[days[i]] = days[i];
}

document.write(“days[\”Monday\”]:”+days[“Monday”]);
</script>
This produces
days[“Monday”]:Monday
90.How to use “join()” to create a string from an array using JavaScript?
“join” concatenates the array elements with a specified seperator between them.

<script type=”text/javascript”>
var days = [“Sunday”,”Monday”,”Tuesday”,”Wednesday”, “Thursday”,”Friday”,”Saturday”];
document.write(“days:”+days.join(“,”));
</script>
This produces
days:Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
91.How to make a array as a stack using JavaScript?
The pop() and push() functions turn a harmless array into a stack

<script type=”text/javascript”>
var numbers = [“one”, “two”, “three”, “four”];
numbers.push(“five”);
numbers.push(“six”);
document.write(numbers.pop());
document.write(numbers.pop());
document.write(numbers.pop());
</script>
This produces
sixfivefour
92.How to shift and unshift using JavaScript?
<script type=”text/javascript”>
var numbers = [“one”, “two”, “three”, “four”];
numbers.unshift(“zero”);
document.write(” “+numbers.shift());
document.write(” “+numbers.shift());
document.write(” “+numbers.shift());
</script>
This produces
zero one two
shift, unshift, push, and pop may be used on the same array. Queues are easily implemented using combinations.
93.How to create an object using JavaScript?
var myMovie = new Object();
myMovie.title = “Aliens”;
myMovie.director = “James Cameron”;
…OR…
function movie(title, director) {
this.title = title;
this.director = director;
}
var aliens = new movie(“Aliens”,”Cameron”);
…OR…
function movie(title, director) {
title : title;
director : director;
}
var aliens = new movie(“Aliens”,”Cameron”);

94.How to associate functions with objects using JavaScript?
this.title = title;
this.director = director;
this.toString = function movieToString() {
return(“title: “+this.title+” director: “+this.director);
}
…OR…
this.title = title;
this.director = director;
this.toString = movieToString; //assign function to this method pointer
95.eval()?
The eval() method is incredibly powerful allowing you to execute snippets of code during exection.
var USA_Texas_Austin = “521,289”;
eval(“USA_”+”Texas_”+”Austin”)
96.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.
97.How to create a function using function constructor?
The following example illustrates this
It creates a function called square with argument x and returns x multiplied by itself.
var square = new Function (“x”,”return x*x”);
98.What’s Prototypes for JavaScript?
Objects have “prototypes” from which they may inherit fields and functions.

<script type=”text/javascript”>
function movieToString() {
return(“title: “+this.title+” director: “+this.director);
}
function movie(title, director) {
this.title = title;
this.director = director || “unknown”; //if null assign to “unknown”
this.toString = movieToString; //assign function to this method pointer
}
movie.prototype.isComedy = false; //add a field to the movie’s prototype
var officeSpace = new movie(“OfficeSpace”);
var narnia = new movie(“Narni”,”Andrew Adamson”);
document.write(narnia.toString());
document.write(“
Narnia a comedy? “+narnia.isComedy);
officeSpace.isComedy = true; //override the default just for this object
document.write(“
Office Space a comedy? “+officeSpace.isComedy);
</script>
99.unescape(), escape() ?
These are similar to the decodeURI() and encodeURI(), but escape() is used for only portions of a URI.
var myvalue = “Sir Walter Scott”;
escape(myvalue);

&author=”+escape(myvalue);
100.decodeURI(), encodeURI() ?
Many characters cannot be sent in a URL, but must be converted to their hex encoding. These functions are used to convert an entire URI (a superset of URL) to and from a format that can be sent via a URI.
<script type=”text/javascript”>
var uri = “http://www.google.com/search?q=sonofusion Taleyarkhan”
document.write(“Original uri: “+uri);
document.write(“<br />encoded: “+encodeURI(uri));
</script>