YouTube Icon

Interview Questions.

Top 50 Java Script Interview Questions - Jul 26, 2022

fluid

Top 50 Java Script Interview Questions

Q1. How To Comment Javascript Code?

Use // for line comments and

/*

*/ for block feedback

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

GET: Parameters are surpassed inside the querystring. Maximum quantity of facts that may be sent through the GET method is restricted to approximately 2kb.

POST: Parameters are exceeded within the request frame. There isn't any restrict to the quantity of facts that may be trferred the use of POST. However, there are limits on the most amount of statistics that can be trferred in a single call/cost pair.

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

<script type="text/javascript">

feature pseudoHitMe() 

alert("Ouch!");

</script>

<a href="javascript:pseudoHitMe()">hit me</a>

Q4. What Does The "get right of entry to Is Denied" Ie Error Mean?

The "Access Denied" error in any browser is because of the following reason.

A javascript in one window or body is tries to get entry to any other window or frame whose document's domain isn't like the record containing the script.

Q5. How Do You Submit A Form Using Javascript?

Use file.Bureaucracy[0].Submit();

(0 refers back to the index of the form – when you have a couple of shape in a web page, then the first one has the index zero, 2nd has index 1 and so on 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's far that as a programming language, the vocabulary of the middle language is compact as compared to full-fledged programming languages. If you already software in Java or C, you virtually need to unlearn some standards that had been overwhelmed into you. For example, JavaScript is a loosely typed language, which me that a variable would not care if it is keeping a string, a range of, or a reference to an object; the equal variable can even alternate what type of information it holds while a script runs.

The other part of JavaScript implementation in browsers that makes it simpler to study is that maximum of the items you script are pre-described for the writer, and that they largely constitute physical things you may see on a page: a text box, an photograph, and so forth. It's simpler to mention, "OK, these are the matters I'm running with and I'll use scripting to lead them to do such and such," instead of having to dream up the consumer interface, conceive of and code gadgets, and cope with the interaction between items and customers. With scripting, you have a tendency to write down a _lot_ less code.

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

Characteristic getCookieData(labelName) 

//from Danny Goodman

var labelLen = labelName.Length;

// study cookie assets best as soon as for velocity

var cookieData = record.Cookie;

var cLen = cookieData.Period;

var i = zero;

var cEnd;

even as (i < cLen) 

var j = i + labelLen;

if (cookieData.Substring(i,j) == labelName) 

cEnd = cookieData.IndexOf(";",j);

if (cEnd == -1) 

cEnd = cookieData.Duration;

go back unescape(cookieData.Substring(j+1, cEnd));

i++;

return "";

 

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

Feature init() 

setValueFromCookie("brand");

setValueFromCookie("market");

setValueFromCookie("measure");

 

function setValueFromCookie(widget) 

if( getCookieData(widget) != "") 

report.GetElementById(widget).Fee = getCookieData(widget);

//in case you call your cookies the widget ID, you may use the following helper function

function setCookie(widget) 

file.Cookie = widget + "=" +

break out(record.GetElementById(widget).Price) + getExpirationString();

 

Q11. How To Detect The Operating System On The Client Machine?

In order to detect the running gadget on the consumer gadget, the navigator.AppVersion string (assets) must be used.

Q12. How To Change Style On An Element?

Between CSS and javascript is a unusual symmetry. CSS fashion guidelines 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 instance: 

file.GetElementById("myText").Style.Shade = "green";

file.GetElementById("myText").Style.FontSize = "20";

-or-

document.GetElementById("myText").ClassName = "everyday";

Q13. How Do You Assign Object Properties?

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

Q14. How To Add Buttons In Javascript?

The maximum fundamental and historical use of buttons are the "post" and "clear", which appear slightly before the Pleistocene length. Notice when the "GO!" button is pressed it submits itself to itself and appends the call within 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 method is to set the "kind" to "button" and use the "onclick" occasion. 

<script type="text/javascript">

feature 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 purchaser-facet script it does require the net server's help for its computation,so it is constantly faster than any server-facet script like ASP,PHP,etc..

Q16. What Is The Difference Between Undefined Value And Null Value?

(i)Undefined value cannot be explicitly stated this is there is no keyword called undefined while null price has keyword known as null

(ii)typeof undefined variable or belongings returns undefined whereas typeof null fee returns item

Q17. What Is === Operator ?

==== is strict equality operator ,it returns authentic only when the 2 operands are having the identical value with none kind conversion.

Q18. How To Reload The Current Page

window.Area.Reload(actual);

Q19. How To Use "be part of()" To Create A String From An Array Using Javascript?

"be a part of" concatenates the array elements with a distinct seperator between them.

<script type="text/javascript">

var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];

file.Write("days:"+days.Be a part of(","));

</script>

This produces

days:Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday

Q20. How To Disable An Html Object

file.GetElementById("myObject").Disabled = proper;

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

Values stored in cookies won't have semicolons, commas, or areas. You ought to use the accessible "break out()" feature to encode the values, and "unescape()" to retrieve them.

//Sets cookie of modern-day value for myTextBox

function TextBoxOnchange() 

var myBox = window.Record.GetElementById(myTextBox");

document.Cookie = "myTextBox="+ get away(myBox.Fee) + getExpirationString();

 

//return a string like ";expires=Thu, five Jan 2006 16:07:fifty two UTC"

function getExpirationString() 

var exp = new Date();

var threemonths = exp.GetTime()+(one hundred twenty*24*60*60*one thousand);

exp.SetTime(threemonths);

go back ";expires="+exp.ToGMTString();

 

This is called from the event handler within 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 of the variables and items used inside the application ,but it does no longer delete variables declared with var key-word.

Q23. Can Javascript Code Be Broken In Different Lines?

Breaking is feasible within a string announcement through the use of a backslash on the stop but not inside every other javascript statement.

This is ,

file.Write("Hello global");

is viable however not document.Write

("hi there global");

Q24. How About 2+five+"eight"?

Since 2 and five are integers, this is number mathematics, since 8 is a string, it’s concatenation, so seventy eight is the result.

Q25. What Is Negative Infinity?

It’s a number in JavaScript, derived by way of dividing bad quantity by zero.

Q26. What Are Undefined And Undeclared Variables?

Undeclared variables are those who aren't declared within the application (do not exist in any respect),looking to study their values gives runtime mistakes.But if undeclared variables are assigned then implicit assertion is carried out .

Undefined variables are those who are not assigned any fee but are declared in the application.Trying to study such variables offers unique value known as undefined value.

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

Javascripts run on the consumer facet which saves the server roundtrip time for small processing. It me that it makes web pages extra interactive as the entirety isn't always required to be submitted on the server. Let’s recall a small clock if managed by the server then the trmission time will make the clock defective in this situation 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 strategies that permit emitting of purchaser-facet JavaScript: 

RegisterClientScriptBlock and RegisterStartupScript. 

Example usage: 

Page.RegisterClientScriptBlock("ScriptKey", "<script language=javascript>" + "characteristic TestFn()  alert('Clients-facet JavaScript'); </script>"); 

Page.RegisterStartupScript("ScriptKey", "<script language=javascript>" + "characteristic TestFn()  alert('Clients-side JavaScript'); </script>"); 

ScriptKey is used to suppress the equal JavaScript from being emitted more than once. Multiple calls to RegisterClientScriptBlock or RegisterStartupScript with the same value of ScriptKey emit the script most effective once, on the first call.

Q29. How To Create Arrays In Javascript?

We can claim an array like this 

var scripts = new Array(); 

We can add factors to this array like this

scripts[0] = "PHP";

scripts[1] = "ASP";

scripts[2] = "JavaScript";

scripts[3] = "HTML";

Now our array scrips has 4 factors inner it and we are able to print or get admission to them by way of the usage of their index variety. Note that index variety starts from @To get the third detail of the array we need to use the index number 2 . Here is the manner to get the 1/3 detail of an array. 

File.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 underneath exact style of comments <script language=javascript> <!-- javascript code goes here // --> or Use the <NOSCRIPT>some html code </NOSCRIPT> tags and code the show html statements between these and this could appear on the web page if the browser does not guide javascript

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

This may be finished by using the usage of the following tag among head tags or among frame tags.

<script src="abc.Js"></script>How to get entry to an external javascript record this is saved externally and now not embedded? In which abc.Js is the external javscript document to be accessed.

Q32. What's Relationship Between Javascript And Ecmascript?

ECMAScript is but another name for JavaScript (other names consist of LiveScript). The cutting-edge JavaScript which you see supported in browsers is ECMAScript revision three.

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 on the Status bar</a>

Look on the Status bar as your cursor goes over the hyperlink.

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

Security of a form can be ensured by way of several ways some of them are:-

@ Action Attribute of the form- The shape movement attribute should begin with https:// for making sure the secure web site.

@ Checking the Java Routine- In the Java habitual theformname.Action="particular URL” which need to additionally start with https:// for ensuring the secure web site.

@ Checking the URL of the shape itself whether it starts offevolved with https://

Any one of the circumstance have to be obeyed by means of the web shape else the form isn't always 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 mounted base of browsers will only worsen. By definition, it could by no means enhance until really absolutely everyone on the earth threw away their old browsers and upgraded to the state-of-the-art gee-whiz variations. But even then, there are masses of discrepancies among the scriptability of the trendy Netscape Navigator and Microsoft Internet Explorer. 

The state of affairs makes scripting a mission, specifically for learners who won't be privy to the restrictions of earlier browsers. A lot of attempt in my books and ancillary fabric is going towards assisting scripters recognise what capabilities paintings wherein browsers and the way to both workaround boundaries in earlier browsers or boost the compatibility commonplace denominator. 

Designing scripts for a Web web site requires making some difficult choices approximately if, whilst, and how to put into effect the blessings scripting gives a web page to your target audience. For public Web sites, I propose the use of scripting in an additive way: let enough content stand on its personal, but let scriptable browser users acquire an better enjoy, ideally with the same HTML record.

Q36. How To Embed Javascript In A Web Page?

Javascript code may be embedded in a web 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 largest hassle. It calls for understanding how every scriptable browser model implements its object model. You see, the incompatibility rarely has to do with the center JavaScript language (although there had been upgrades to the language over the years); the majority of incompatibility issues need to do with the item models that every browser version implements. For instance, scripters who began out with Navigator 3 implemented the picture rollover because it seemed cool. But they had been 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 selection work on more recent browsers without traumatic older ones, it turned into a painful mastering enjoy for plenty.

The 2d largest can of worms is scripting connections between multiple windows. A lot of scripters want to have little home windows pop up with navigation bars or some such gizmos. But the item models, specifically within the older browser variations, don't make it easy to paintings with those home windows the minute you positioned a consumer in front of them--customers who can manually near home windows or alternate their stacking order. More these days, a glitch in some uninstall exercises for Windows 95 packages can disturb critical components of the gadget Registry that Internet Explorer 4 requires for managing a couple of home windows. A scripter can not work round this problem, because it's no longer viable to discover the problem in a user's device. I generally tend to avoid multiple windows that interact with every different. I assume a variety of green Web surfers can also get pressured by them.

Q38. How To Convert Numbers To Strings Using Javascript?

You can prepend the quantity 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(sixteen);

mystring could be "e".

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

Use the "fee" property.

Var myValue = window.Record.GetElementById("MyTextBox").Fee;

Q40. Are Java And Javascript The Same?

No.Java and javascript are  distinct languages.

Java is a powerful object - orientated programming language like C++,C while Javascript is a customer-aspect scripting language with a few boundaries.

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

<script> characteristic setFocus()  if(focusElement != null) 

record.Paperwork[0].Elements["myelementname"].Focus();   </script>

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

Var checkedP = window.File.GetElementById("myCheckBox").Checked;

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

JavaScript is a purchaser facet scripting language that is specifically used to perform consumer aspect processing to save you server round journeys and to make the user response time faster. It is widely used for validation purpose consisting of affirm password validation and and so on. It is generally embedded within the HTML which on purchaser aspect is interpreted with the aid of the browser and the scripts are replica able.

Q44. How To Create A Function Using Function Constructor?

The following instance illustrates this

It creates a function called square with argument x and returns x extended by using itself.

Var rectangular = 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 textual content = myWidget.Fee;

var OK = re.Test(text);

if( ! OK ) 

alert("The extra parameters want some paintings.Rn Should be something like: "&a=1&c=four"");

 

Q46. How To Make Elements Invisible

Change the "visibility" characteristic of the style item related to your detail. Remember that a hidden detail nevertheless takes up space, use "display" to make the distance disappear as nicely.

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>

feature favAnimal(button) 

alert('You like '+button.Fee+'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 "file.Write()" ?

Changing the contents of an detail is a miles higher answer. When the method showStatus is invoked it'll trade the content of the span. 

...

Function showStatus(message) 

var detail = document.GetElementById("mystatus");

element.TextContent = message; //for Firefox

detail.InnerHTML = message; //for IE (why can't all of us just get alongside?)

return true;

...

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

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

Sticky session is a characteristic which affords load balancing solution for internet farms for re-routing the request of the session to the gadget which first wered the request for that session. This ensures the consultation persistency in case whilst the consultation is routed to different servers. Sticky session reasons choppy load distribution across servers.

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

Use the parseInt() feature, that takes a string because the first parameter, and the bottom as a 2nd parameter. So to transform hexadecimal 3F to decimal, use parseInt ("3F", 16);




CFG