Java Script Interview Questions & Answers

Java Script Interview Questions

Are you prepared in attending an interview? Then do not worry, we’ve a right answer for your job interview preparation. If you are preparing for Java Script job interview and don’t know how to crack interview and what level or difficulty of questions to be asked in job interviews then go through Wisdomjobs Java Script interview questions and answers page to crack your job interview. JavaScript, often abbreviated as JS, is a high-level, interpreted programming language of HTML and the Web. It is designed for creating network-centric applications. It is complimentary to and integrated with Java. It is easy to implement. Below is the list of frequently asked Java Script interview questions and answers which gets you ready to face the interviews:

Java Script Interview Questions And Answers

Java Script Interview Questions
    1. Question 1. What Is Javascript?

      Answer :

      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.

    2. Question 2. How To Read And Write A File Using Javascript?

      Answer :

      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.

    3. Question 3. What Are Javascript Types?

      Answer :

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

    4. Question 4. How Do You Convert Numbers Between Different Bases In Javascript?

      Answer :

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

    5. Question 5. What Can Javascript Programs Do?

      Answer :

      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.

    6. Question 6. What Is The Data Type Of Variables Of In Javascript?

      Answer :

      All variables are of object type in JavaScript.

    7. Question 7. Is A Javascript Faster Than An Asp Script?

      Answer :

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

    8. Question 8. Are Java And Javascript The Same?

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

    9. Question 9. How To Embed Javascript In A Web Page?

      Answer :

      javascript code can be embedded in a web page between <script  langugage="javascript"></script> tags

    10. Question 10. How Is Javascript Different From Java?

      Answer :

      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.

    11. Question 11. What's Relationship Between Javascript And Ecmascript?

      Answer :

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

    12. Question 12. How Do You Submit A Form Using Javascript?

      Answer :

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

    13. Question 13. How To Detect The Operating System On The Client Machine?

      Answer :

      In order to detect the operating system on the client machine, the navigator.appVersion string (property) should be used.

    14. Question 14. 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?

      Answer :

      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.

    15. Question 15. How To Create Arrays In Javascript?

      Answer :

      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 or access them by using their index number. Note that 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. 
      We also can create an array like this 
      var no_array = new Array(21, 22, 23, 24, 25);

    16. Question 16. How Do You Target A Specific Frame From A Hyperlink?

      Answer :

      Include the name of the frame in the target attribute of the hyperlink. <a href=”mypage.htm” target=”myframe”>>My Page</a>

    17. Question 17. What Is A Fixed-width Table And Its Advantages?

      Answer :

      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.

    18. Question 18. Example Of Using Regular Expressions For Syntax Checking In Javascript

      Answer :

      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\"");

    19. Question 19. How To Add Buttons In Javascript?

      Answer :

      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" />

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

      <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;" />

    20. Question 20. How To Set A Html Document's Background Color?

      Answer :

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

    21. Question 21. How Can Javascript Be Used To Personalize Or Tailor A Web Site To Fit Individual Users?

      Answer :

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

    22. Question 22. Are You Concerned That Older Browsers Don't Support Javascript And Thus Exclude A Set Of Web Users? Individual Users?

      Answer :

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

    23. Question 23. What Does Isnan Function Do?

      Answer :

      Return true if the argument is not a number.

    24. Question 24. What Is Negative Infinity?

      Answer :

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

    25. Question 25. In A Pop-up Browser Window, How Do You Refer To The Main Browser Window That Opened It?

      Answer :

      Use window.opener to refer to the main window from pop-ups.

    26. Question 26. Methods Get And Post In Html Forms - What's The Difference?.

      Answer :

      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.

    27. Question 27. How To Write A Script For "select" Lists Using Javascript

      Answer :

      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. 

    28. Question 28. Text From Your Clipboard?

      Answer :

      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. Question 29. What Does The "access Is Denied" Ie Error Mean?

      Answer :

      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.

    30. Question 30. What Are The Problems Associated With Using Javascript, And Are There Javascript Techniques That You Discourage?

      Answer :

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

    31. Question 31. What Boolean Operators Does Javascript Support?

      Answer :

      &&, || and !

    32. Question 32. What Does "1"+2+4 Evaluate To?

      Answer :

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

    33. Question 33. What Are The Ways To Emit Client-side Javascript From Server-side Code In

      Answer :

      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.

    34. Question 34. What Is The Difference Between Registerclientscriptblock And Registerstartupscript?

      Answer :

      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.

    35. Question 35. What Is The Difference Between A Web-garden And A Web-farm?

      Answer :

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

    36. Question 36. How To Get The Contents Of An Input Box Using Javascript?

      Answer :

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

    37. Question 37. How To Determine The State Of A Checkbox Using Javascript?

      Answer :

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

    38. Question 38. How To Set The Focus In An Element Using Javascript?

      Answer :

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

    39. Question 39. How To Access An External Javascript File That Is Stored Externally And Not Embedded?

      Answer :

      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 javscript file to be accessed.

    40. Question 40. What Is The Difference Between An Alert Box And A Confirmation Box?

      Answer :

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

    41. Question 41. What Is A Prompt Box?

      Answer :

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

    42. Question 42. Can Javascript Code Be Broken In Different Lines?

      Answer :

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

    43. Question 43. Taking A Developer's Perspective, Do You Think That That Javascript Is Easy To Learn And Use?

      Answer :

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

    44. Question 44. How About 2+5+"8"?

      Answer :

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

    45. Question 45. What Is The Difference Between Sessionstate And Viewstate?

      Answer :

      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.

    46. Question 46. What Does The Enableviewstatemac Setting In An Aspx Page Do?

      Answer :

      Setting EnableViewStateMac=true is a security measure that allows ASP.NET to ensure that the viewstate 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 viewstate 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.

    47. Question 47. How To Accessing Elements Using Javascript?

      Answer :

      To do something interesting with HTML elements, we must first be able to uniquely identify which element we want. In the example 
      <form action="">
      <input type="button" id="useless" name="mybutton" value="doNothing" />

      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] = "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;

      <form name="beerForm" action="">
      <select name="beer">
      <option selected="selected">Select Beer</option>
      <option>Amstel Light</option>
      <option>Corona Light</option>

      <input type="button" name="submitbutton" value="Drink"
      onclick="showStatus()" />

    48. Question 48. What Looping Structures Are There In Javascript?

      Answer :

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

    49. Question 49. To Put A "close Window" Link On A Page ?

      Answer :

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

    50. Question 50. How To Hide Javascript Code From Old Browsers That Dont Run It?

      Answer :

      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

    51. Question 51. How To Comment Javascript Code?

      Answer :

      Use // for line comments and

      */ for block comments

    52. Question 52. Name The Numeric Constants Representing Max,min Values

      Answer :


    53. Question 53. What Does Javascript Null Mean?

      Answer :

      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.

    54. Question 54. How Do You Create A New Object In Javascript?

      Answer :

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

    55. Question 55. How Do You Assign Object Properties?

      Answer :

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

    56. Question 56. What Is This Keyword?

      Answer :

      It refers to the current object.

    57. Question 57. 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?

      Answer :

      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.

    58. Question 58. You Have An 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. What Could Be One Reason That Is Causing This Error?

      Answer :

      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.

    59. Question 59. To Set All Checkboxes To True Using Javascript?

      Answer :

      //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;

    60. Question 60. How To Select An Element By Id And Swapping An Image ?

      Answer :

      <script language="JavaScript" type="text/javascript" >
      function setBeerIcon() {
      var beerIcon = document.getElementById("beerIcon");
      beerIcon.src = "images/"+getSelectValue("beer")+".jpg";
      <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>

    61. Question 61. What Does Undefined Value Mean In Javascript?

      Answer :

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

    62. Question 62. What Is The Difference Between Undefined Value And Null Value?

      Answer :

      (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

    63. Question 63. What Is Variable Typing In Javascript?

      Answer :

      It is perfectly legal to assign a number to a variable and then assign a string to the same variable as follows 
      i = 10;
      i = "string";
      This is called variable typing

    64. Question 64. Does Javascript Have The Concept Level Scope?

      Answer :

      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.

    65. Question 65. What Are Undefined And Undeclared Variables?

      Answer :

      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.

    66. Question 66. What Is === Operator ?

      Answer :

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

    67. Question 67. How To Find The Selected Radio Button Immediately Using The 'this' Variable?

      Answer :

      function favAnimal(button) {
      alert('You like '+button.value+'s.');
      <input type="radio" name="marsupial" value="kangaroo"
      <br /><input type="radio" name="marsupial" value="Opossum" 
      <br /><input type="radio" name="marsupial" value="Tasmanian Tiger"
      onchange="favAnimal(this)">Tasmanian Tiger

    68. Question 68. How To Find Radio Button Selection When A Form Is Submitted?

      Answer :

      <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) {
      alert("You selected ""+myForm.marsupial[i].value+"".");
      <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()" />

    69. Question 69. How To Disable An Html Object

      Answer :

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

    70. Question 70. To Write Messages To The Screen Without Using "document.write()" ?

      Answer :

      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>

    71. Question 71. How To Add New Elements Dynamically.

      Answer :

      <html xmlns="" xml:lang="en" lang="en">
      <script type="text/javascript">
      function addNode() {
      var newP = document.createElement("p");
      var textNode = document.createTextNode(" I'm a new text node");
      <body onload="addNode();" style=" background: url('../images/Sand-1280.jpg'); background-color: yellow;">
      <p id="firstP">firstP<p>

    72. Question 72. How To Have An Element Invoke A Javascript On Selection, Instead Of Going To A New Url:

      Answer :

      <script type="text/javascript">
      function pseudoHitMe() {
      <a href="javascript:pseudoHitMe()">hit me</a>

    73. Question 73. How To Have The Status Line Update When The Mouse Goes Over A Link (the Support Of The Status Line Is Sporadic)?

      Answer :

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

    74. Question 74. How To Create A Popup Warning Box

      Answer :

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

    75. Question 75. How To Create A Confirmation Box?

      Answer :

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

    76. Question 76. How To Create An Input Box?

      Answer :

      prompt("What is your temperature?");

    77. Question 77. How To Open A Window With No Toolbar, But With The Location Object.

      Answer :"","Pennies","resizable=yes, status=yes,toolbar=yes,location=yes,menubar=yes,scrollbars=yes,width=800,height=400");

    78. Question 78. How To Setting A Cookie With The Contents Of A Textbox ?

      Answer :

      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);
      return ";expires="+exp.toGMTString();

      This is called from the event handler in the HTML.

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

    79. Question 79. How To Getting Values From Cookies To Set Widgets?

      Answer :

      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));
      return "";

      //init() is called from the body tag onload function.
      function init() {

      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();

    80. Question 80. How To Change Style On An Element?

      Answer :

      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 "". The class of an element can be swapped out. For example: 
      document.getElementById("myText").style.color = "green";
      document.getElementById("myText").style.fontSize = "20";
      document.getElementById("myText").className = "regular";

    81. Question 81. How To Make Elements Invisible

      Answer :

      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) { = 'visible';
      } else { = 'hidden';

    82. Question 82. How To Set The Cursor To Wait.

      Answer :

      In theory, we should cache the current state of the cursor and then put it back to its original state. = 'wait'; 
      //do something interesting and time consuming = 'auto'; 

    83. Question 83. How To Reload The Current Page

      Answer :


    84. Question 84. How To Force A Page To Go To Another Page Using Javascript?

      Answer :

      <script language="JavaScript" type="text/javascript" ><!-- location.href= "http://newhost /newpath /newfile.html";  //--></script>

    85. Question 85. How To Convert A String To A Number Using Javascript?

      Answer :

      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

    86. Question 86. How To Convert Numbers To Strings Using Javascript?

      Answer :

      You can prepend the number with an empty string 
      var mystring = ""+myinteger; 
      var mystring = myinteger.toString(); 
      You can specify a base for the conversion, 
      var myinteger = 14; 
      var mystring = myinteger.toString(16);
      mystring will be "e".

    87. Question 87. How To Test For Bad Numbers Using Javascript?

      Answer :

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

    88. Question 88. What's Math Constants And Functions Using Javascript?

      Answer :

      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

    89. Question 89. What's The Date Object Using Javascript?

      Answer :

      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"

    90. Question 90. What Does The Delete Operator Do?

      Answer :

      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.

    91. Question 91. How To Delete An Entry Using Javascript?

      Answer :

      The "delete" operator removes an array element, but oddly does not change the size of the array.
      <script type="text/javascript">
      var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
      document.write("Number of days:"+days.length); delete days[4];
      document.write("<br />Number of days:"+days.length);
      This produces
      Number of days:7
      Number of days:7

    92. Question 92. How To Use Strings As Array Indexes Using Javascript?

      Answer :

      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];
      This produces

    93. Question 93. How To Use "join()" To Create A String From An Array Using Javascript?

      Answer :

      "join" concatenates the array elements with a specified seperator between them.

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

    94. Question 94. How To Make A Array As A Stack Using Javascript?

      Answer :

      The pop() and push() functions turn a harmless array into a stack

      <script type="text/javascript">
      var numbers = ["one", "two", "three", "four"];
      This produces

    95. Question 95. How To Shift And Unshift Using Javascript?

      Answer :

      <script type="text/javascript">
      var numbers = ["one", "two", "three", "four"];
      document.write(" "+numbers.shift());
      document.write(" "+numbers.shift());
      document.write(" "+numbers.shift());
      This produces
      zero one two
      shift, unshift, push, and pop may be used on the same array. Queues are easily implemented using combinations.

    96. Question 96. What Does Break And Continue Statements Do?

      Answer :

      Continue statement continues the current loop (if label not specified) in a new iteration whereas break statement exits the current loop.

    97. Question 97. How To Create A Function Using Function Constructor?

      Answer :

      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. Question 98. What's Prototypes For Javascript?

      Answer :

      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");
      Narnia a comedy? "+narnia.isComedy);
      officeSpace.isComedy = true; //override the default just for this object
      Office Space a comedy? "+officeSpace.isComedy);

    99. Question 99. Unescape(), Escape()

      Answer :

      These are similar to the decodeURI() and encodeURI(), but escape() is used for only portions of a URI.

      <script type="text/javascript">
      var myvalue = "Sir Walter Scott";
      document.write("Original myvalue: "+myvalue);
      document.write("<br />escaped: "+escape(myvalue));
      document.write("<br />uri part: \"&author="+escape(myvalue)+"\"");

      If you use escape() for the whole URI... well bad things happen.
      <script type="text/javascript">
      var uri = " Taleyarkhan"
      document.write("Original uri: "+uri);
      escaped: "+escape(uri));

    100. Question 100. Decodeuri(), Encodeuri()

      Answer :

      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 = " Taleyarkhan"
      document.write("Original uri: "+uri);
      document.write("<br />encoded: "+encodeURI(uri));

    101. Question 101. What Is The Difference Between Javascript And Jscript?

      Answer :

      Jscript supports more rich set of functionality/commands than the java script, through which ActiveX and local computer can be accessed. These commands are used in an intranet where the connecting computer’s configuration is known and they are all being accessed using Internet Explorer. While java script targets unknown machine configuration and Jscript cannot for which java script are suitable for internet which Jscripts are not.

    102. Question 102. What Is Java Script And What Are Their Functionalities?

      Answer :

      JavaScript is a client side scripting language that is mainly used to perform client side processing to prevent server round trips and to make the user response time faster. It is widely used for validation purpose such as confirm password validation and etc. It is generally embedded within the HTML which on client side is interpreted by the browser and the scripts are copy able.

    103. Question 103. What Is The Main Difference Between Client Side Javascript And Server Side Java Script? How Actually They Run On Both Side?

      Answer :

      To state the main difference, JavaScript at the client side does not require a web server to make it run instead it uses the client’s processor for this purpose. This eradicates the portability issue. But in server side JavaScript deployment, portability, configuration are major and vast issues and requires a web server to run the script within a page before rendering its output as a response html page.

    104. Question 104. What Are The Methods Of Validating Whether The Form Is Secure?

      Answer :

      Security of a form can be ensured by several ways some of them are:-
      1. Action Attribute of the form- The form action attribute must start with https:// for ensuring the secure site.
      2. Checking the Java Routine- In the Java routine theformname.action="specified URL” which should also begin with https:// for ensuring the secure site.
      3. Checking the URL of the form itself whether it begins with https://
      Any one of the condition should be obeyed by the web form else the form is not secured.

    105. Question 105. How Can Javascript Make A Web Site Easier To Use?

      Answer :

      Javascripts run on the client side which saves the server roundtrip time for small processing. It means that it makes web pages more interactive as everything is not required to be submitted at the server. Let’s consider a small clock if controlled by the server then the transmission time will make the clock faulty in this case javascript is used.

    106. Question 106. What Does Sticky Session Mean In A Web-farm Scenario?

      Answer :

      Sticky session is a characteristic which provides load balancing solution for web farms for re-routing the request of the session to the machine which first answered the request for that session. This ensures the session persistency in case when the session is routed to other servers. Sticky session causes uneven load distribution across servers.

    107. Question 107. How Do We Get Javascript Onto A Web Page?

      Answer :

      The script element can directly be added inside the body of the page. It should start with the tag <script> and end with </script> tag. The script can also be added to the head tag of the web page. Similarly the other way is by placing the script in a separate file which gets downloaded on the client’s machine when the page is requested.

    108. Question 108. Discuss How Can We Access Elements Using Java Script?

      Answer :

      Each elements of JavaScript can be accessed by their names. To access the page, document element is used and to access the browser the windowelement is used in the script. This element’s values are required for several computing reason say validation check. For example:
      var myID = windows.document.formLogin.userID.value;

    109. Question 109. What Is Decodeuri(), Encodeuri() In Javascript?

      Answer :

      In order to transform the URL into its hexadecimal equivalent the encodeURI() and decodeURI() are used. This is done to send the characters that by default cannot be specified in a URL.

      For example, the following code snippet performs the encoding of URL:

                var uri =; // original URI
                var encodeuri=encodeURI(uri);
                document.write("<br />necodeuri”);
                var decodeuri = decodeURI(ncodeuri); 

    110. Question 110. What Are Windows Object And Navigator Object In Javascript?

      Answer :

      The top level object in java script is the windows object. It further has several other objects such as document, location, history, menu bar, name, etc. contained within itself. The global object on which client side java scripts are written is the windows object. Information regarding the client system is returned by the Navigator browser of the script. For all users Navigator browsers are the base object.

    111. Question 111. How To Read And Write A File Using Java Script?

      Answer :

      This can be done in two ways which are discussed below,
      1.      Using an ActiveX objects (Internet Explorer only)
      Using ActiveX objects, following should be included in the code to read a file
      var fso = new ActiveXObject("Scripting.FileSystemObject");
      var s = fso.OpenTextFile("C:\\example.txt", 1, true);
      2.      By the use of JavaScript extensions which runs from the Java Script editor.
      In JavaScript Extensions,
      fh = fopen(getScriptPath(), 0); to open a file

    112. Question 112. Discuss The Relationship Between Javascript And Ecmascript?

      Answer :

      Javascript is a scripting language that has been widely accepted for client side web development. However it originated from ECMA standards. ECMA and livescripts are just other names of java script.

    113. Question 113. What Are The Different Modules In Spring Framework?

      Answer :

      ► The Core container module
      ► Application context module
      ► AOP module (Aspect Oriented Programming)
      ► JDBC abstraction and DAO module
      ► O/R mapping integration module (Object/Relational)
      ► Web module
      ► MVC framework module

Java Script Related Tutorials

Java Script Related Interview Questions

Java Script Related Practice Tests

Popular Interview Questions

All Interview Questions

Java Script Practice Test

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

Java Script Tutorial