JavaScript also known as JS in short, is a server-side programming language. JavaScript is widely used for building various web applications. Below we have discussed questions related to basic JS to advanced JS that are likely to be asked in the interview. The list covers all the JavaScript Questions for freshers as well as professional level candidates. These questions will act as a guide to help you crack the interview and achieve your dream job.
Q1. Define JavaScript?
JavaScript is a client-side and server-side scripting language that is embedded in HTML pages, that is understood by web browsers. It can also be called an object-oriented programming language.
Q2. What is the difference between Java and JavaScript?
Java can be defined as a programming language whereas JavaScript is a coded program that is embedded into HTML Pages. JavaScript is a client-side scripting language and Java is a structured object-oriented programming language. These two languages are not at all dependent and are designed with different intentions.
Q3. What is isNaN Function used for?
isNaN function returns the value if the argument is not a number and false if it is a number.
Q4. Between JavaScript and an ASP Script which one is faster?
JavaScript is a client-side scripting language and does not require a web server to execute whereas ASP is a server-side scripting language, hence JavaScript is faster than ASP Script. Now JavaScript is also a server-side language and is called nodejs.
Q5. Define negative infinity?
Negative infinity is defined as a number in JavaScript that is derived by the division of a negative number by zero.
Q6. Can JavaScript Code be broken into several lines?
Breaking the code within the string can be done by adding the backlash” /” at the end of the first line.
For Example:
document. Write ("This is \a program,");
Q7. JavaScript was developed by which company?
Netscape is a software company that developed JavaScript.
Q8. What is meant by undeclared and undefined variables?
Undeclared variables that are not declared and are non-existable in the program. In case the program tries to read the undeclared variable values then a run time error occurs.
Undefined variables are those variables that are declared within the variable but no values are assigned to them. When the program is run then an undefined value is returned.
Q9. Write down a code that adds new elements dynamically?
<html> <head> <title>Hello Javascript</title> <script type="text/javascript"> function addNode () { var newP = document. createElement("p"); var textNode = document.createTextNode(" This is a new text node"); newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP); } </script> </head> <body> <p id="firstP">firstP<p> </body> </html>
Q10. Define global variables and how are they declared?
Global Variables can be declared throughout the program. To declare the local variable or object “var” keyword is used, if you remove this “var” keyword then it is taken as a global variable.
For Example:
// Declare a global: globalVariable = “Test”;
Q11. Name JavaScript Datatypes?
JavaScript Datatypes are:
- Number
- String
- Boolean
- Object
- Undefined
Q12. What is meant by the prompt box?
A prompt box provides the user with a text box in which the input is entered. To enter the text or number, a label and a box are provided.
Q13. What is the ‘this’ keyword referred to in JavaScript?
‘This’ is referred to the object from that was called.
Q14. Explain the working of the timers?
Timers are when a particular piece of code is to execute at a given time or they are also used in the repetition of code at a set time. The function setTimeout (function, delay) function is used to start a timer that is used to call a particular function after a certain delay. The setInterval (function, delay) function executes the function repeatedly and only stops when canceled. The clearInterval(id) function instructs the timer to stop.
Q15. Name the symbols that are used for comments in JavaScript?
// for Single line comments and /* Multi Line Comment */
Q16. Differentiate between the ViewState and SessionState?
View page refers to the specific page in the session. Session State refers to the specific data that can be accessed from all web application pages.
Q17. What is meant by the “===” operator?
“===” is called an equality operator. It returns true in case the two operands have the same values without any conversion.
Q18. How to submit a form using JavaScript?
Submit the form using JavaScript;
document.form[0].submit();
document.form[0].submit();
Q19. Is automatic type conversion supported in JavaScript?
Yes, automatic conversion is supported in JavaScript.
Q20. How style/class of an element in JavaScript changed?
There are two ways:
document.getElementById("myText"). style. fontSize = "20"; or document. getElementById ("myText"). className = "anyclass";
Q21. How to read/ write a file in JavaScript?
There are two ways by which you can read/write a file in JavaScript
- By using JavaScript extensions.
- By using a web page and Active X objects.
Q22. Name the looping structures in JavaScript?
There are three looping structures:·
- For loop.
- While loop.
- Do-while loop.
Q23. What is meant by variable typing in JavaScript?
Variable typing is used when there is assigning a number to a variable. Also, the same can be assigned to a string.
For example:
i = 10; i = "string;"
Q24. Which function is used to convert the string of any base to an integer in JavaScript?
The parse Int () function is used to convert the string into an integer. It does this by accepting the first parameter as a string and the second parameter is the base “
Example:
Convert 4F or base 16, the code will look like this: parseInt ("4F", 16);
Q25. Differentiate between “==” and ‘===”?
“==” is used for checking the equality among the values whereas “===” is used when for checking the equality more strictly. It returns the value false if any of the values or the variable type are different.
Q26. What will be the result of 3+2+”7”?
3 and 2 are integers so they will automatically add up where 7 is a string therefore concatenation will be done. Hence the result will be 57.
Q27. How can the operating system be detected on the client machine?
Platform string feature can be used to detect the operating system on the client machine.
Q28. What is meant by NULL in JavaScript?
The NULL value denotes no value or no object which implies no object or null string, no array object, and no valid Boolean value.
Q29. Define the function of the delete operator?
The delete keyword is used when it is required to delete the property and its value.
Example:
var student= {age:, batch:"ABC"}; Delete student. age;
Q30. What is meant by undefined value in JavaScript?
Undefined value refers to the:
- The variable that has been used in the code does not exist.
- Property is non-existable.
- The variable is not assigned any value.
Q31. Name the type of Pop up boxes in JavaScript?
- Alert
- Confirm
- Prompt
Q32. What is Void (0) used for?
Void (0) is used to avoid the page from getting refreshed and the parameter zero is passed during the calling. It is also used without refreshing the page by calling another method.
Q33. Give a code that can force a page to load another page JavaScript?
The following code can be used:
<script language="JavaScript" type="text/javascript" > location.href="https://javascript-interview-questions-answers.html"; </script>
Q34. What are the datatypes of variables used in JavaScript?
The data types of variables in JavaScript are object data types.
Q35. Differentiate between a confirmation box and an alert box?
A confirmation has two buttons namely ok and cancels whereas the alert box has one button which is the ok button.
Q36. Define escape characters?
Escape Characters or backslash are used while working with special characters such as single quotes, double quotes, apostrophes, and ampersands.
Q37. Define JavaScript Cookies?
JavaScript is defined as small files that temporarily store information on the computer whenever the user visits the site.
Q38. Define the pop () method in JavaScript?
The pop () method takes the value of the last array and returns it and the array that was called on is altered.
var cloths = ["dress", "coat", "shirt"]; cloths.pop(); //Now cloth becomes dress,coat
Q39. Is JavaScript having a concept-level scope?
No JavaScript does not consist of concept-level scope.
Q40. Name some of the disadvantages of using innerHTML in JavaScript?
- The innerHTML is reparsed and the is converted into elements making it slower.
- The replacement of the content occurs everywhere.
- For example “appending to innerHTML is restricted.
Q41. What is the difference between break and continue?
The break statement is used to exit from the current loop whereas the continue statement is used to continue with the next statement in the loop.
Q43. What are the groups of data types in JavaScript?
There are two types of groups of data types namely primitive data types and Reference data types.
Q44. How can you create generic objects?
Generic objects can be created using
var I = new object();
Q45. Why is the “type” operator used?
Type operator is used when the type of variable string description is to be returned.
Q46. What is the keyword used to handle exceptions?
The try and catch keyword is used to handle exceptions.
Try{ Code } Catch(exp){ Code to throw an exception. } Finally{ Code runs either it finishes successfully or after catch }
Q47. What is the keyword used that will print the text on the screen?
To print the text on the screen Document. Write is used
Q48. Why is the Blur function used?
The blur function is used to eliminate the focus from the specific object.
Q49. Define Variable Typing?
Variable typing is used to assign a number to a variable and then to the same variable assign a string.
Q50. What is used to find an operating system in the client machine in JavaScript?
The Navigator app version is used to find the operating system in the client machine.
Q51. List different types of errors in JavaScript?
There are three types of errors in JavaScript:
- Load Time errors: Errors that occur during the loading of the web page.
- Run Time errors: this type of error occurs because of the incorrect use of the command in the HTML language.
- Logical Error: this occurs due to incorrect use of logic that is performed on the function.
Q52. What is the use of the Push method?
The push method is used to append one or more elements to an array end and this method can also be used for appending multiple elements by passing multiple arguments.
Q53. Differentiate between JavaScript and Jscript?
Both JavaScript and Jscript are the same. JavaScript is owned by Netscape and Jscript is owned by Microsoft.
Q54. How does the assigning of the object properties take place in JavaScript?
Objects properties are assigned to the object in the following way:
obj ["class"] = 10; or obj.class = 10;
Q55. Define ‘Strict Mode and how to enable it?
The strict mode helps to show the error in the code that are difficult to detect as well it also detects the error that hampers the working of the JavaScript engines.
Strict mode can be added the following way:
function myfunction() { "use strict;" var v = "This is a strict mode function"; }
Q56. How can we retrieve the status of the checkbox?
The status can be retrieved the following way:
alert(document.getElementById(‘checkbox1’).checked);
Q57. How to detect the OS of the client machine?
OS of the client machine can be detected by using the navigator.appVersion.
Q58. Define window.onload and on document ready?
The onload function only runs when the whole information of the page is loaded and this makes this execution process slow.
The onDocumentReady only runs when the DOM is loaded and therefore allows early manipulation of the code.
Q59. Explain the working of closure?
The closure is a variable that is declared locally related to a function that remains in the memory when it is returned.
For Example :
function greet(message) { console.log(message); } function greeter(name, age) { return name + " says howdy!! He is " + age + " years old"; } // Generate the message var message = greeter("James", 23); // Pass it explicitly to greet greet(message); This function can be better represented by using closures function greeter(name, age) { var message = name + " says howdy!! He is " + age + " years old"; return function greet() { console.log(message); }; } // Generate the closure var JamesGreeter = greeter("James", 23); // Use the closure JamesGreeter();
Q60. How to add a value to an array?
The value of an array can be done in the following way:
arr[arr.length] = value;
Q61. Define the for-in loop In JavaScript?
The for-in loop is used for looping through the properties.
for (variable name in object){ statement or block to execute }
Q62. What is an anonymous function in JavaScript?
An anonymous function is defined as a function that is declared without any named identifier.
Syntax for declaring anonymous function:
var anon = function() { alert('I am anonymous'); }; anon();
Q63. Differentiate between. call () and. apply ()?
.call function is used when the number of arguments used by the programmer is known to them whereas the .apply function is used when the number of arguments is unknown.
The main difference between the two is the way the arguments are passed:
var someObject = { myProperty : 'Foo', myMethod : function(prefix, postfix) { alert(prefix + this.myProperty + postfix); } }; someObject.myMethod('<', '>'); // alerts '<Foo>' var someOtherObject = { myProperty : 'Bar.' }; someObject.myMethod.call(someOtherObject, '<', '>'); // alerts '<Bar>' someObject.myMethod.apply(someOtherObject, ['<', '>']); // alerts '<Bar>'
Q64. Define event bubbling?
In JavaScript, DOM elements can be nested within each other. In such cases, if the handler of the child is clicked then the handler of the parent will work a similar way.
Q65. Is JavaScript case sensitive?
Yes, JavaScript is case sensitive like parseInt function is different from the parseint.
Q66. Which Boolean operators are used in JavaScript?
The ‘And’ Operator (&&), ‘Or’ Operator (||), and the ‘Not’ Operator (!) are used.
Q67. What is the syntax for targeting the particular frame from a hyperlink in JavaScript?
This is the following syntax:
<a href=”/newpage.htm” target=”newframe”>>New Page</a>
Q68.Define the role of break and continue statements?
The break statement helps in getting out of the current loop and the continue statement continues the current loop.
Q69. Differentiate between a web garden and a web farm?
Web Garden and Web Farm are both hosting systems. A web garden is a system that has many processors included in one server whereas a web farm is a much larger system that uses more than many servers.
Q70. How properties of the object are assigned?
Object properties are assigned similarly to the values are assigned to the variable. For example, form action value is assigned to submit in the following way Document. form.action=”submit”
Q71. Name the method for reading and writing a file in JavaScript?
The method for reading and writing a file in JavaScript is by using JavaScript extensions for example to open the file the following is the syntax:
fh = fopen(getScriptPath(), 0);
Q72. How is the DOM utilized?
Document Object Model determines how the various objects in the document interact with each other. DOM is used while developing web pages.
Q73. Explain the utilization of event handlers?
The event handler’s main purpose is to manage the proper execution of the events like clicking on the links. These are the greatest attributes of the object and include the name of the event and the action in case the event takes place.
Q75. What is the use of deffered scripts?
Sometimes during the HTML code parsing the loading of the page is stopped until the script stops executing. If the script is heavy then the web page is delayed. Here comes the role of the deffered script, it delays the execution time of the script until the HTML parser is running and this further helps to reduce the loading time of the web page.
Q76. Name various functional components in JavaScript?
- First-class function: These functions can be passed as arguments to the other functions.
- Nested Functions: These functions are defined within other functions.
Q77. Explain errors in JavaScript?
- Load-time error: This error is shown during the loading of the page and occurs due to the wrong use of syntax.
- Run-time error: This error occurs while running the program. Eg: illegal operations.
- Logic error: This error occurs when the logic is not correct for example an infinite loop.
Q78. Define Screen Objects?
Screen objects help in reading the information from the client screen.
Below are the properties of the screen object:
- AvailHeight: height of the client’s screen.
- AvailWidth: width of the client’s screen.
- ColorDepth: bit depth of images on the client’s screen.
- Height: total height of the client’s screen, and also the taskbar.
- Width: total width of the client’s screen, and also the taskbar.
Q79. Define unshift () method?
Unshift () method is used to append the desired number of elements to the array top. Example:
var name = [ "lily" ]; name.unshift( "miley" ); name.unshift( "emily", "Jane" ); console.log(name); the output of the above will be as below: [" emily,"," Jane ,", " miley ", " lily "]
Q80. Define the unescaped () and escape () functions?
The escape is used to code a string and then transfer it from one computer to across the network.
Example:
<script> document.write(escape("Hello? How are you!")); </script>
The output will be.
Hello%3F%20How%20are%20you%21 The escape () function is responsible for decoding the string. Example: script> document.write(unescape("Hello%3F%20How%20are%20you%21")); </script> Output will be: Hello? How are you!
Q81. Define the decodeURI () and encodeURI()?
EncodeURI () is used for converting URL into hex coding and decodeURI () is used to convert the encoded URL back to original.
<script> var uri="my test.asp?name=ståle&car=saab"; document.write(encodeURI(uri)+ "<br>"); document.write(decodeURI(uri)); </script> Output: my%20test.asp?name=st%C3%A5le&car=saab mytest.asp?name=ståle&car=saab
Q82. Why can’t you use the innerHTML in JavaScript?
The innerHTML is refreshed again and again and thus it becomes slower. Hence the scope of validation in innerHTML is finished.
Q83. What is the following denoting?
var myArray = [[[]]];
The above syntax is declaring a three-dimensional array.
Q84. Define namespacing and its use?
Namespacing is used for grouping the desired functions or variables under a unique name. These benefits reusing the code.
Q85. How can we hide the JavaScript code from the old browsers that do not support JavaScript?
To hide the JavaScript code one can, use:
Add “<!–” without the quotes in the code just after the <script> tag.
Add “//–>” without the quotes in the code just before the <script> tag.
Q86. What is the use of a loop in JavaScript?
Loops are useful when you require to execute the same line of code a certain number of times.
Q87. What is the syntax for the all types of loops?
For loop:
Syntax:
for(statement1; statement2; statment3) { lines of code to be executed }
Example:
<html> <head> <script type="text/javascript"> var students = new Array("Emily", "Mann", "Aaron", "Edwick", "Elizabeth"); document.write("<b>Using for loops </b><br />"); for (i=0;i<students.length;i++) { document.write(students[i] + "<br />"); } </script> </head> <body> </body> </html>
while loop;
Syntax:
while(condition) { lines of code to be executed }
Do-While loop:
Syntax: do { block of code to be executed } while (condition)
Example:
<html> <head> <script type="text/javascript"> document.write("<b>Using while loops </b><br />"); var i = 0, j = 1, k; document.write("Fibonacci series less than 40<br />"); while(i<40) { document.write(i + "<br />"); k = i+j; i = j; j = k; } </script> </head> <body> </body> </html>
Q88. Name JavaScript array methods?
JavaScript array methods are:
length property –> tells the number of elements in an array.
prototype property –> adds new properties and methods.
reverse method –> reverses the order of items in an array.
sort method –> sort the items in an array.
pop method –>removes the last item of an array.
shift method –> removes the first item of an array.
push method –> add a value as the last item of the array.
Q89. Explain the OOPS concept in JavaScript?
Creating objects in JavaScript that act like real-life objects helps in making programming easier.
Syntax for creating objects:
var objName = new Object(); objName.property1 = value1; objName.property2 = value2; objName.method1 = function() { line of code }
Q90. How can we loop through the properties of an Object?
To loop through the properties of an object for/in a loop is used. Variable can be anything but the object name should be the same throughout the code.
Syntax:
for (variablename in objectname) { lines of code to be executed }
Example:
<html> <head> <script type="text/javascript"> var employee={first:"John", last:"Doe", department:"Accounts"}; var details = ""; document.write("<b>Using for/in loops </b><br />"); for (var x in employee) { details = x + ": " + employee[x]; document.write(details + "<br />"); } </script> </head> <body> </body> </html>
Q91. Define JavaScript Unit Testing and the challenges in it?
JavaScript unit testing tests the code written for a web page. To check whether the functionalities work properly, as an inline event handler it is combined with HTML and then executed in browser. These unit tests are then combined in the test suite.
Challenges of JavaScript Unit Testing:
- JavaScript does not support unit testing in run time environment.
- Some JavaScript have multiple dependencies.
- JavaScript when combine with HTML and CSS performs well rather than the web.
- There are problems with page rendering and DOM manipulation.
- Sometime error occurs displaying the message “unable to load example.js”
Solution:
- Avoid using global variables.
- Avoid manipulating predefined objects.
- Create functionalities in smaller fragments that are less dependent.
Q92. Name some of the important JavaScript Unit Testing Framework?
Unit.js: It is called an open-source assertion library running on browser and Node.js. , providing the full documented API of the assertion list.
QUnit: It is used for both client-side and server-side JavaScript Unit Testing. and is freely available. It is used for jQuery projects and follows the Common JS unit testing Specification for unit testing in JavaScript.
Jasmine: Jasmine is a behavior-driven development framework to unit test JavaScript that is used for testing both synchronous and asynchronous JavaScript codes. DOM is not required.
Karma: It is an open-source productive testing environment that has easy workflow control running on the command line. This provides the facility to run the test on real devices with easy debugging.
Mocha: Mocha runs on Node.js as well as in the browser. Mocha easily performs asynchronous testing. Provides accuracy and flexibility in reporting.
Jest: Jest is used by Facebook to test all the JavaScript code. It gives the ‘zero-configuration testing experience and provides support to both independent and non-interrupting running tests without any conflict.
AVA: AVA is a simple JavaScript Unit Testing Framework. Tests that run in parallel and serially. Parallel tests run without interrupting each other. Asynchronous testing is also done.
Q93. Explain Quicksort Algorithm in JavaScript?
Quicksort algorithm works on the divide and conquers method by dividing the element into smaller based on certain conditions and performing operations on these divided smaller parts.
Basic Steps for Quicksort Algorithm:
- First, select an element that will be called the pivot
- Next, compare all array elements with the selected pivot element and arrange them so that elements less than the pivot element are left. Greater than pivot is to its right.
- Finally, perform the same operations on the left and right side elements to the pivot element.
Q94. What are the steps included in the working of Quick Sort?
Step 1) First, find the “pivot” element in the array.
Step 2) Start the left pointer at the first element of the array.
Step 3) Start the right pointer at the last element of the array.
Step 4) Compare the element pointing with the left pointer, and if it is less than the pivot element, then move the left pointer to the right (add 1 to the left index). Continue this until the left side element is greater than or equal to the pivot element.
Step 5) Compare the element pointing with the right pointer. If it is greater than the pivot element, move the right pointer to the left (subtract 1 to the right index). Continue this until the right-side element is less than or equal to the pivot element.
Step 6) Check if the left pointer is less than or equal to a right pointer, then saw the elements in these pointers’ locations.
Step 7) Increment the left pointer and decrement the right pointer.
Step 8) If the left pointer index is still less than the right pointer’s index, repeat the process; else, return the left pointer’s index.
Q94. Define DOM in JavaScript?
With the help of the Document Object Model (DOM), JavaScript can easily access all the objects. When the page is loaded then the web browser creates the DOM of the webpages.
Q95. How can we use DOM and Events?
JavaScript can also react to existing events and create new events on the page through:
getElementById, innerHTML Example:
<html> <head> <title>DOM!!!</title> </head> <body> <h3 id="one">Welcome</h3> <p>This is the welcome message.</p> <h3>Technology</h3> <p>This is the technology section.</p> <script type="text/javascript"> var text = document.getElementById("one").innerHTML; alert("The first heading is " + text); </script> </body> </html>
- getElementById: To access elements and attributes whose id is set.
- innerHTML: To access the content of an element.
getElementByTagName Example:
<html> <head> <title>DOM!!!</title> </head> <body> <h3>Welcome</h3> <p>This is the welcome message.</p> <h3>Technology</h3> <p id="second">This is the technology section.</p> <script type="text/javascript"> var paragraphs = document.getElementsByTagName("p"); alert("Content in the second paragraph is " + paragraphs[1].innerHTML); document.getElementById("second").innerHTML = "The orginal message is changed."; </script> </body> </html>
Event Handler:
- createElement: To create new element
- removeChild: Remove an element
- you can add an event handler to a particular element like this
Example:
<html> <head> <title>DOM!!!</title> </head> <body> <input type="button" id="btnClick" value="Click Me!!" /> <script type="text/javascript"> document.getElementById("btnClick").addEventListener("click", clicked); function clicked() { alert("You clicked me!!!"); } </script> </body> </html>
Q96. Define External JavaScript with an example?
To avoid coping of the code on the several pages which is time consuming you can use external JavaScript through the below syntax;
<script type=”text/javascript,” src=”/currentdetails.js,”>
Example: var currentDate = new Date(); var day = currentDate.getDate(); Var month = currentDate.getMonth() + 1; var monthName; var hours = currentDate.getHours(); var mins = currentDate.getMinutes(); var secs = currentDate.getSeconds(); var strToAppend; It (hours >12 ) { hours1 = "0" + (hours - 12); strToAppend = "PM"; } else if (hours <12) { hours1 = "0" + hours; strToAppend = "AM"; } else { hours1 = hours; strToAppend = "PM"; } if(mins<10) mins = "0" + mins; if (secs<10) secs = "0" + secs; switch (month) { case 1: monthName = "January"; break; case 2: monthName = "February"; break; case 3: monthName = "March"; break; case 4: monthName = "April"; break; case 5: monthName = "May"; break; case 6: monthName = "June"; break; case 7: monthName = "July"; break; case 8: monthName = "August"; break; case 9: monthName = "September"; break; case 10: monthName = "October"; break; case 11: monthName = "November"; break; case 12: monthName = "December"; break; } var year = currentDate.getFullYear(); var myString; myString = "Today is " + day + " - " + monthName + " - " + year + ".<br />Current time is " + hours1 + ":" + mins + ":" + secs + " " + strToAppend + "."; document.write(myString);
The above example is used to display the current time and date on all web pages.
Q97. Where to use Internal and External JavaScript Code?
JavaScript Internal Code is used when there are only a few lines of code whereas in case JavaScript code is for many webpages try to keep it in a separate file which external JavaScript for easy debugging.
Q98. How can you create cookies in JavaScript?
Cookies in JavaScript can be created using document.cookie property:
document.cookie = “cookiename=cookievalue”
The cookie will close when the user closes the browser:
document.cookie = “cookiename=cookievalue; expires= Thu, 21 Aug 2014 20:00:00 UTC”
To access the cookie:
var x = document.cookie
Example:
<html> <head> <title>Cookie!!!</title> <script type="text/javascript"> function createCookie(cookieName,cookieValue,daysToExpire) { var date = new Date(); date.setTime(date.getTime()+(daysToExpire*24*60*60*1000)); document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString(); } function accessCookie(cookieName) { var name = cookieName + "="; var allCookieArray = document.cookie.split(';'); for(var i=0; i<allCookieArray.length; i++) { var temp = allCookieArray[i].trim(); if (temp.indexOf(name)==0) return temp.substring(name.length,temp.length); } return ""; } function checkCookie() { var user = accessCookie("testCookie"); if (user!="") alert("Welcome Back " + user + "!!!"); else { user = prompt("Please enter your name"); num = prompt("How many days you want to store your name on your computer?"); It (user!="" && user!=null) { createCookie("testCookie", user, num); } } } </script> </head> <body onload="checkCookie()"></body> </html>
Q99. Tell an example of JavaScript Multiplication Table?
Example:
<html> <head> <title>Multiplication Table</title> <script type="text/javascript"> var rows = prompt("How many rows for your multiplication table?"); var cols = prompt("How many columns for your multiplication table?"); if(rows == "" || rows == null) rows = 10; if(cols== "" || cols== null) cols = 10; createTable(rows, cols); function createTable(rows, cols) { var j=1; var output = "<table border='1' width='500' cellspacing='0'cellpadding='5'>"; for(i=1;i<=rows;i++) { output = output + "<tr>"; while(j<=cols) { output = output + "<td>" + i*j + "</td>"; j = j+1; } output = output + "</tr>"; j = 1; } output = output + "</table>"; document.write(output); } </script> </head> <body> </body> </html>
Q100. Show a Popup Message using an event with an example?
Below example displays a simple message “Welcome” with a popup” Welcome to my WebPage”:
Example:
<html> <head> <title>Event!!!</title> <script type="text/javascript"> function trigger() { document.getElementById("hover").addEventListener("mouseover", popup); function popup() { alert("Welcome to my WebPage!!!"); } } </script> <style> p{ font-size:50px; position: fixed; left: 550px; top: 300px; } </style> </head> <body onload="trigger();"> <p id="hover">Welcome!!!</p> </body> </html>