Top 50 Java Script Interview Questions You Must Prepare 27.Jul.2024

Q1. How To Comment Javascript Code?

Use // for line comments and
/*

*/ for block comments

Q2. 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 trferred using POST. However, there are limits on the maximum amount of data that can be trferred in one name/value pair.

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

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

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

Q6. What Boolean Operators Does Javascript Support?

&&, || and !

Q7. To Put A "close Window" Link On A Page ?

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

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

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

Q10. How To Getting Values From Cookies To Set Widgets?

function getCookieData(labelName) {
//from Danny Goodman
var labelLen = labelName.length;
// read cookie property only once for speed
var cookieData = document.cookie;
var cLen = cookieData.length;
var i = 0;
var cEnd;
while (i < cLen) {
var j = i + labelLen;
if (cookieData.substring(i,j) == labelName) {
cEnd = cookieData.indexOf(";",j);
if (cEnd == -1) {
cEnd = cookieData.length;
}
return unescape(cookieData.substring(j+1, cEnd));
}
i++;
}
return "";
}

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

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

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

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

Q12. How To Change Style On An Element?

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

Q13. How Do You Assign Object Properties?

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

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

Q15. Is A Javascript 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..

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

Q17. What Is === Operator ?

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

Q18. How To Reload The Current Page

window.location.reload(true);

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

Q20. How To Disable An Html Object

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

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

Values stored in cookies may not have semicolons, commas, or spaces. You should use the handy "escape()" function to encode the values, and "unescape()" to retrieve them.

//Sets cookie of current value for myTextBox
function TextBoxOnchange() {
var myBox = window.document.getElementById(myTextBox");
document.cookie = "myTextBox="+ escape(myBox.value) + getExpirationString();
}

//return a string like ";expires=Thu, 5 Jan 2006 16:07:52 UTC"
function getExpirationString() {
var exp = new Date();
var threemonths = exp.getTime()+(120*24*60*60*1000);
exp.setTime(threemonths);
return ";expires="+exp.toGMTString();
}

This is called from the event handler in the HTML.

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

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

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

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

Q25. What Is Negative Infinity?

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

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

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

Javascripts run on the client side which saves the server roundtrip time for small processing. It me 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 trmission time will make the clock faulty in this case javascript is used.

Q28. What Are The Ways To Emit Client-side Javascript From 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.

Q29. How To Create Arrays In Javascript?

We can declare an array like this 
var scripts = new Array(); 
We can add elements to this array like this

scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";

Now our array scrips has 4 elements inside it and we can print or access them by using their index number. Note that index number starts from @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);

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

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

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

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

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

Security of a form can be ensured by several ways some of them are:-
@ Action Attribute of the form- The form action attribute must start with https:// for ensuring the secure site.
@ Checking the Java Routine- In the Java routine theformname.action="specified URL” which should also begin with https:// for ensuring the secure site.
@ 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.

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

Q36. How To Embed Javascript In A Web Page?

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

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

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

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

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

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

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

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

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

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

Q43. What Is Java Script And What Are Their Functionalities?

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.

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

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

Q46. 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';
}

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

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

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

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

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