Javascript Interview Questions and Answers:-
CLICK HERE for JAVASCRIPT MCQs —> Objective Questions
1. Define 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?
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 Define 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.
3. Define what’s the 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?
You can use several different methods of placing javascript in your pages.
You can directly add a script element inside the body of the page.
- For example, to add the “last updated line” to your pages, In your page text, add the following:
<p>blah, blah, blah, blah, blah.</p>
<script type=”text/javascript” >
<!– Hiding from old browsers
document.write(“Last Updated:” +
document.lastModified);
document.close();
// –>
</script>
<p>yada, yada, yada.</p>
(Note: the first comment, “<–” hides the content of the script from browsers that don’t understand javascript. The “// –>” finishes the comment. The “//” tells javascript that this is a comment so javascript doesn’t try to interpret the “–>”. If your audience has much older browsers, you should put this comments inside your javascript. If most of your audience has newer browsers, the comments can be omitted. For brevity, in most examples here the comments are not shown. )
The above code will look like this on Javascript enabled browsers,
- Javascript can be placed inside the <head> element
Functions and global variables typically reside inside the <head> element.
<head>
<title>Default Test Page</title>
<script language=”JavaScript” type=”text/javascript”>
var myVar = “”;
function timer(){setTimeout(‘restart()’,10);}
document.onload=timer();
</script>
</head> - Javascript can be referenced from a separate file
Javascript may also a placed in a separate file on the server and referenced from an HTML page. (Don’t use the shorthand ending “<script … />). These are typically placed in the <head> element.
<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 are 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. With the help of that popup list of links, the user with a scriptable browser can bypass one intermediate menu page. The user without a scriptable browser (or who has disabled JavaScript) will have to drill down through a more traditional and time-consuming path to the desired content.
9. How can JavaScript be used to improve the “look and feel” of a Web site? By the same token, how can JavaScript be used to improve the user interface?
On their own, Web pages tend to be lifeless and flat unless you add animated images or more bandwidth-intensive content such as Java applets or other content requiring plug-ins to operate (ShockWave and Flash, for example).
Embedding JavaScript into an HTML page can bring the page to life in any number of ways. Perhaps the most visible features built into pages recently with the help of JavaScript are the so-called image rollovers: roll the cursor atop a graphic image and its appearance changes to a highlighted version as a feedback mechanism to let you know precisely Define what you’re about to click on. But there are less visible yet more powerful enhancements to pages that JavaScript offers.
Interactive forms validation is an extremely useful application of JavaScript. While a user is entering data into form fields, scripts can examine the validity of the data–did the user type any letters into a phone number field? for instance. Without scripting, the user has to submit the form and let a server program (CGI) check the field entry and then report back to the user. This is usually done in a batch mode (the entire form at once), and the extra transactions take a lot of time and server processing power. Interactive validation scripts can check each form field immediately after the user has entered the data, while the information is fresh in the mind.
Another helpful example is embedding small data collections into a document that scripts can look up without having to do all the server programming for database access. For instance, a small company could put its entire employee directory on a page that has its own search facility built into the script. You can cram a lot of text data into scripts no larger than an average image file, so it’s not like the user has to wait forever for the data to be downloaded.
Other examples abound, such as interactive tree-structure tables of contents. More modern scriptable browsers can be scripted to pre-cache images during the page’s initial download to make them appear lickety-split when needed for image swapping. I’ve even written some multi-screen interactive applications that run entirely on the client, and never talk to the server once everything is downloaded.
10. Define what are JavaScript types?
Number, String, Boolean, Function, Object, Null, Undefined.
11. 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);
12. 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 have 4 elements inside it and we can print or access them by using their index number. Note that the index number starts from 0. To get the third element of the array we have to use the index number 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);
13. 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=”my frame”>>My Page</a>
14. Define 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.
15. 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.rn Should be something like: ”&a=1&c=4””);
}
16. 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” />
<br />
<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>
17. 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 FilesNetscapeUsersusernamecookies.txt
In the case of IE, each cookie is stored in a separate file namely [email protected].
c:[email protected]
18. Define 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
19. How to set an HTML document’s background color?
document.bgcolor property can be set to any appropriate color.
20. How can JavaScript be used to personalize or tailor a Web site to fit individual users?
JavaScript allows a Web page to perform “if-then” kinds of decisions based on browser version, operating system, user input, and, in more recent browsers, details about the screen size in which the browser is running. While a server CGI program can make some of those same kinds of decisions, not everyone has access to or the expertise to create CGI programs. For example, an experienced CGI programmer can examine information about the browser whenever a request for a page is made; thus a server so equipped might serve up one page for Navigator users and a different page for Internet Explorer users. Beyond the browser and operating system version, a CGI program can’t know more about the environment. But a 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.
21. Are you concerned that older browsers don’t support JavaScript and thus exclude a set of Web users? individual users?
Fragmentation of the installed base of browsers will only get worse. By definition, it can never improve unless absolutely everyone on the planet threw away their old browsers and upgraded to the latest gee-whiz versions. But even then, there are plenty of discrepancies between the scriptability of the latest Netscape Navigator and Microsoft Internet Explorer.
The situation makes scripting a challenge, especially for newcomers who may not be aware of the limitations of earlier browsers. A lot of effort in my books and ancillary material goes toward helping scripters know Define what features work in which browsers and how to either workaround limitations in earlier browsers or raise the compatibility common denominator.
Designing scripts for a Web site requires making some hard decisions about if, when, and how to implement the advantages scripting offers a page to your audience. For public Web sites, I recommend using scripting in an additive way: let sufficient content stand on its own, but let scriptable browser users receive an enhanced experience, preferably with the same HTML document.
22. Define what does isNaN function do?
Return true if the argument is not a number.
23. Define what is negative infinity?
It’s a number in JavaScript, derived by dividing a negative number by zero.
24. 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.
25. Define what is the data type of variables in JavaScript?
All variables are of the object type in JavaScript.
26. Methods GET and POST in HTML forms – Define what’s the difference?
GET: Parameters are passed in the query string. The 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.
27. How to write a script for “Select” lists using javascript
- To remove an item from a list set it to null
mySelectObject.options[3] = null; - To truncate a list set its length to the maximum size you desire
mySelectObject.length = 2; - To delete all options in a select object set the length to 0.
mySelectObject.leng
28. 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.
29. Define 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 trying to access another window or frame whose document’s domain is different from the document containing the script.
30. 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..
31. 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.
32. How to embed javascript in a web page?
javascript code can be embedded in a web page between <script
langugage=”javascript”></script> tags
33. Define what and where are the best JavaScript resources on the Web?
The Web has several FAQ areas on JavaScript. The best place to start is something called the meta-FAQ [14-Jan-2001 Editor’s Note: I can’t point to it anymore, it is broken!], which provides a high-level overview of the JavaScript help available on the Net. As for fact-filled FAQs, I recommend one maintained by Martin Webb and a mini-FAQ that I maintain.
For interactive help with specific problems, nothing beats the primary JavaScript Usenet newsgroup, comp.lang.javascript. Depending on my work backlog, I answer questions posted there from time to time. Netscape and Microsoft also have vendor-specific developer discussion groups as well as detailed documentation for the scripting and object model implementations.
34. Define what are the problems associated with using JavaScript, and are there JavaScript techniques that you discourage?
Browser version incompatibility is the biggest problem. It requires knowing how each scriptable browser version implements its object model. You see, the incompatibility rarely has to do with the core JavaScript language (although there have been improvements to the language over time); the bulk of incompatibility issues have to do with the object models that each browser version implements. For example, scripters who started out with Navigator 3 implemented the image rollover because it looked cool. But they were dismayed to find out that the image object wasn’t scriptable in Internet Explorer 3 or Navigator 2. While there are easy workarounds to make this feature work on newer browsers without disturbing older ones, it was a painful learning experience for many.
The second biggest can of worms is scripting connections between multiple windows. A lot of scripters like to have little windows pop up with navigation bars or some such gizmos. But the object models, especially in the older browser versions, don’t make it easy to work with these windows the minute you put a user in front of them–users who can manually close windows or change their stacking order. More recently, a glitch in some uninstalls routines for Windows 95 applications can disturb vital parts of the system Registry that Internet Explorer 4 requires for managing multiple windows. A scripter can’t work around this problem, because it’s not possible to detect the problem in a user’s machine. I tend to avoid multiple windows that interact with each other. I think a lot of inexperienced Web surfers can also get confused by them.
35. Define what boolean operators does JavaScript support?
&&, || and !
36. Define what does “1”+2+4 evaluate to?
Since 1 is a string, everything is a string, so the result is 124.
37. Define what are the ways to emit client-side JavaScript from the server-side code in ASP.NET?
The Page object in ASP.NET has two methods that allow emitting of client-side JavaScript:
RegisterClientScriptBlock and RegisterStartupScript.
Example usage:
Page.RegisterClientScriptBlock(“ScriptKey”, “<script language=javascript>” + “function TestFn() { alert(‘Clients-side JavaScript’); }</script>”);
Page.RegisterStartupScript(“ScriptKey”, “<script language=javascript>” + “function TestFn() { alert(‘Clients-side JavaScript’); }</script>”);
ScriptKey is used to suppress the same JavaScript from being emitted more than once. Multiple calls to RegisterClientScriptBlock or RegisterStartupScript with the same value of ScriptKey emit the script only once, on the first call.
38. Define what is the difference between RegisterClientScriptBlock and RegisterStartupScript?
RegisterClientScriptBlock emits the JavaScript just after the opening
tag. RegisterStartupScript emits the JavaScript at the bottom of the ASP.NET page just before the closing
tag.
39. Define what is the difference between a web-garden and a web-farm?
Web-garden – An IIS6.0 feature where you can configure an application pool as a web-garden and also specify the number of worker processes for that pool. It can help improve performance in some cases.
Web-farm – a general term referring to a cluster of physically separate machines, each running a web-server for scalability and performance (contrast this with web-garden which refers to multiple processes on one single physical machine).
40. How to get the contents of an input box using Javascript?
Use the “value” property.
var myValue = window.document.getElementById(“MyTextBox”).value;
41. How to determine the state of a checkbox using Javascript?
var checkedP = window.document.getElementById(“myCheckBox”).checked;
42. How to set the focus in an element using Javascript?
<script> function setFocus() { if(focusElement != null) { document.forms[0].elements[“myelementname”].focus(); } } </script>
43. 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>How to access an external javascript file that is stored externally and not embedded? where abc.js is the external javascript file to be accessed.
44. Define 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.
45. Define what is a prompt box?
A prompt box allows the user to enter input by providing a text box.
46. 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”);
47. Taking a developer’s perspective, do you think that that JavaScript is easy to learn and use?
One of the reasons JavaScript has the word “script” in it is that as a programming language, the vocabulary of the core language is compact compared to full-fledged programming languages. If you already program in Java or C, you actually have to unlearn some concepts that had been beaten into you. For example, JavaScript is a loosely typed language, which means that a variable doesn’t care if it’s holding a string, a number, or a reference to an object; the same variable can even change Define what type of data it holds while a script runs.
The other part of JavaScript implementation in browsers that makes it easier to learn is that most of the objects you script are pre-defined for the author, and they largely represent physical things you can see on a page: a text box, an image, and so on. It’s easier to say, “OK, these are the things I’m working with and I’ll use scripting to make them do such and such,” instead of having to dream up the user interface, conceive of and code objects, and handle the interaction between objects and users. With scripting, you tend to write a _lot_ less code.
48. Define what Web sites do you feel used JavaScript most effectively (i.e., best-in-class examples)? The worst?
The best sites are the ones that use JavaScript so transparently, that I’m not aware that there is any scripting on the page. The worst sites are those that try to impress me with how much scripting is on the page.
49. 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.
50. Define 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.
JAVASCRIPT Questions pdf free download::
51. Define what does the EnableViewStateMac setting in an aspx page do?
Setting EnableViewStateMac=true is a security measure that allows ASP.NET to ensure that the view state for a page has not been tampered with. If on Postback, the ASP.NET framework detects that there has been a change in the value of view state that was sent to the browser, it raises an error – Validation of viewstate MAC failed.
Use <%@ Page EnableViewStateMac=”true”%> to set it to true (the default value, if this attribute is not specified is also true) in an aspx page.
52. How to Accessing Elements using javascript?
To do something interesting with HTML elements, we must first be able to uniquely identify which element we want. In the example
<body>
<form action=””>
<input type=”button” id=”useless” name=”mybutton” value=”doNothing” />
</form>
</body>
We can use the “getElementById” method (which is generally preferred)
document.getElementById(“useless”).style.color = “red”;
or we can use the older hierarchical navigation method,
document.forms[0].mybutton.style.color = “blue”;
Notice that this uses the “name” attribute of the element to locate it.
# Example of Accessing Elements in a DOM.
<script type=”text/javascript” >
function showStatus() {
var selectWidget = document.forms.beerForm.elements[“beer”];
var myValue = selectWidget.options[selectWidget.selectedIndex].value;
alert(‘You drank a ”‘+ myValue +”””);
return true;
}
</script>
<form name=”beerForm” action=””>
<select name=”beer”>
<option selected=”selected”>Select Beer</option>
<option>Heineken</option>
<option>Amstel Light</option>
<option>Corona</option>
<option>Corona Light</option>
<option>Tecate</option>
</select>
<input type=”button” name=”submitbutton” value=”Drink”
onclick=”showStatus()” />
</form>
53. Define what looping structures are there in JavaScript?
for, while, do-while loops, but no foreach.
54. To put a “close window” link on a page ?
<a href=’javascript:window.close()’ class=’mainnav’> Close </a>
55. 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
56. How to comment javascript code?
Use // for line comments and
/*
*/ for block comments
57. Name the numeric constants representing max, min values
Number.MAX_VALUE
Number.MIN_VALUE
58. Define 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.
59. How do you create a new object in JavaScript?
var obj = new Object(); or var obj = {};
60. How to read a Cookie using JavaScript?
Reading a cookie is just as simple as writing one, because of the value of the document. cookie object is the cookie. So you can use this string whenever you want to access the cookie.
The document.cookie string will keep a list of name = value pairs separated by semicolons, where name is the name of a cookie and value is its string value.
You can use strings’ split() function to break the string into key and values.
61. How to delete a Cookie using JavaScript?
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiration date to a time in the past.
62. Define what is this keyword?
It refers to the current object.
63. Define what does the term sticky session mean in a web-farm scenario? Why would you use a sticky session? Define what is the potential disadvantage of using a sticky session?
A sticky session refers to the feature of many commercial loads 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 an 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.
64. You have an ASP.NET web application running on a web-farm that does not use sticky sessions – so the requests for a session are not guaranteed to be served the same machine. Occasionally, the users get error message Validation of viewstate MAC failed. Define what could be one reason that is causing this error?
The most common reason for this error is that the the machinekey value in machine.config is different for each server. As a result, viewstate encoded by one machine cannot be decoded by another. To rectify this, edit the machine.config file on each server in the web-farm to have the same value for machinekey.
65. 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;
}
}
}
66. 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>
67. Define 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.
68. Define what is the difference between undefined value and null value?
- Undefined value cannot be explicitly stated that is there is no keyword called undefined whereas null value has a keyword called null
- type of undefined variable or property returns undefined whereas the type of null value returns object
69. Define 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
70. Does javascript have the concept level scope?
No.Javascript does not have a block-level scope, all the variables declared inside a function possess the same level of scope unlike c,c++, java.
71. Define 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 the 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.
72. Define what is === operator ?
==== is strict equality operator ,it returns true only when the two operands are having the same value without any type conversion.
73. 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
74. 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()” />
75. How to disable an HTML object
document.getElementById(“myObject”).disabled = true;
76. 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>
78. 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>
79. 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>
80. 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.
81. Why it is not advised to use innerHTML in JavaScript?
innerHTML content is refreshed every time and thus is slower. There is no scope for validation in innerHTML and, therefore, it is easier to insert rouge code in the document and, thus, make the web page unstable.
82. Define what does the following statement declares?
var myArray = [[[]]];
var myArray = [[[]]];
It declares a three dimensional array.
83. How are JavaScript and ECMA Script related?
ECMA Script is like rules and guideline while Javascript is a scripting language used for web development.
84. Define what is namespacing in JavaScript and how is it used?
Namespacing is used for grouping the desired functions, variables, etc. under a unique name. It is a name that has been attached to the desired functions, objects, and properties. This improves modularity in coding and enables code reuse.
85. How can JavaScript codes be hidden from old browsers that don’t support JavaScript?
For hiding JavaScript codes from old browsers:
Add “<!–” without the quotes in the code just after the <script> tag.
Add “//–>” without the quotes in the code just before the <script> tag.
Old browsers will now treat this JavaScript code as a long HTML comment. While, a browser that supports JavaScript, will take the “<!–” and “//–>” as one-line comments.