Top 50 Java Script Interview Questions You Must Prepare 25.Jan.2022

Use // for line comments and
/*

*/ for block comments

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.

<script type="text/javascript">
function pseudoHitMe() {
alert("Ouch!");
}
</script>
<a href="javascript:pseudoHitMe()">hit me</a>

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.

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

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

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

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.

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

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

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

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

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>

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

(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

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

window.location.reload(true);

"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

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

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

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.

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

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

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

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.

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.

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.

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

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

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.

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

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

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.

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.

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

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.

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

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

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.

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

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

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.

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

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

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

<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

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>

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.

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