40 Javascript Interview Questions and Answers - Freshers, Experienced

Dear Readers, Welcome to Javascript Interview questions with answers and explanation. These 40 solved Javascript questions will help you prepare for technical interviews and online selection tests conducted during campus placement for freshers and job interviews for professionals.

After reading these tricky Javascript questions, you can easily attempt the objective type and multiple choice type questions on Javascript.
Updated on Feb 12, 2018

What is JavaScript?

JavaScript is an object-based scripting language. It is lightweight and cross-platform and is widely used for client-side validation.

Is there any difference between JavaScript and JScript?

No, both are same. JavaScript was provided by Netscape. Microsoft had just changed its name to Jscript.

Is JavaScript case sensitive language?


Explain the difference between Java and JavaScript.

JavaScript is a client-side scripting language whereas Java is an object-oriented programming language.

JavaScript code runs on a browser only whereas Java application can run both on virtual machine and browser.

JavaScript code are all in text whereas Java code need to be compiled.

What are JavaScript Data Types?

JavaScript comprises of data types such as Number, String, Boolean, Function, Object, Undefined.

Explain the difference between JavaScript and an ASP script.

JavaScript is a client-side language whereas ASP script is a server-side language which requires the assistance of web server to execute. Since JavaScript doesn't require web server for execution, it is faster than ASP script.

What is 'this' keyword in JavaScript?

'This' keyword refers to the object from where it was called.

What are the different actions that are performed using JavaScript?

- JavaScript allows the computer to be more secure by putting the privacy policies and disable the unauthorized access to the files.
- It allows many actions to be performed like, setting the browser's preferences and receiving the request from the servers for the client computer.
- The settings that are used gets saved on the client side on the features like actions buttons, appearance and printing.
- It allows easy launching of an application on the client computer with interactive data to be communicated between the server and the client.
- It allows reading and writing of files or directories on the client or server side.
- It allows easy capturing of the data that is live streamed from the server to the client machine for retransmission.
- It also allows to safe and secure the application from the outside world.

How can JavaScript language be separated from objects?

JavaScript treats and creates the applications for the scripting to make the browser's compatible for use. The language is separated from the objects as it allows the syntax to change the environment. It is a language that keeps the page element in the HTML document. JavaScript allows the elements of the page to remain in sync with the document objects. The language is used to create objects that are connected to page elements and other elements in a language. The separation allows the concept of development and effort to be shared with each factor. The JavaScript language allows dynamic data to be presented using the weakly typed language. It also support any action to be taken to support user interface and graphics.

What is the use of DOM?

DOM is also known as Document Object Model which is used to develop a model with documents or web pages containing objects like elements, links, etc. These objects can be manipulated or certain actions like add, delete or change of an element can be performed using this document object model. Through this change in attributes can be done to get all the list of all the elements in the document. The DOM model responds to API calls that result in documented level of DOM recommendation. It is used to support additional behavior on the web page and use of API give an extensible advantage over other models existing. DOM codes are reused to meet the requirement of the real world and to make all the program interoperable.

What is the importance of <SCRIPT> tag?

- JavaScript is used inside <SCRIPT> tag in HTML document. The tags that are provided the necessary information like alert to the browser for the program to begin interpreting all the text between the tags.
- The <script> tag uses JavaScript interpreter to handle the libraries that are written or the code of the program.
- JavaScript is a case sensitive language and the tags are used to tell the browser that if it is JavaScript enabled to use the text written in between the <Script> and </Script> tags.
- The example is given as :
<SCRIPT> // Starting of the scripting language
//Your code here
</SCRIPT> --> // End of the scripting language
// your code here

Why JavaScript is called as Script for all browsers?

JavaScript is written after <SCRIPT> tag and it is surrounded in between the <!-- your code --> tags, this is also known as comment tag. JavaScript interpreter treats the tag such that it treats all the lines in the comments as script lines. The JavaScript comment starts with // inside the <SCRIPT> tag. The script is contained inside <HTML> tag that contains a comment tag. The browser that is non-compatible with JavaScripts ignore the lines and move on, but compatible browsers always treats it as a script and execute it. The browser treat the written lines between the comment tag as normal lines and just thinking of the comment ignores it. Some browsers just treat the <!-- comment--> as a comment only and ignores whatever is written inside it.

What are the requirements of Web application using JavaScript?

There are lots of application that require certain things when the user uses a JavaScript like:
Data entry validation : This tell that if the field of the form is filled out then during the processing of the server the client side can interact with it.
Serverless CGIs : This describes the processes that are not used with JavaScript but programmed as CGI on server, it gives low performace due to more interaction between the applicatioin and the user.
Dynamic HTML interactivity : It allows dynamic position of the data without using any other scripting language.
CGI prototyping : It allows more reduction of time to access the user interface before implementing the application of the CGI.

What are the different objects used in JavaScripts?

JavaScript uses a hierarchical structure that applies to the objects in a document. There are some objects that show the relationship of one object to another using the language.
Window object :
This is the topmost object in the hierarchy. It represent the content area of browser window that consists of HTML documents. Each frame is also a window that has some actions inside it.
Document object :
This object gets loaded in a window and consists of objects of different kind in the model. It consists of the content that will be written in the script.
Form object :
Form objects are used for more interaction with the users. It represents the form elements inside <FORM>...</FORM> tag.

Why is object naming important to use in JavaScript?

- Object naming is used to create script references to objects while assigning names to every scriptable object in the HTML code. The browsers that are script compatible looks for the optional tags and attributes that enables the assigning of a unique name to each object. The example is :
<form name=”dataEntry” method=get>
<input type=”text” name=”entry”>
<frame src=”info.html” name=”main”>
- The names act as a nametags through which the elements can be easily identified and easily located by the browsers. The references made for each object includes the object hierarchy from the top down. References are used to include names of each object that are coming in the window object. The object naming conventions are easy way to loacte the objects and the linking between them can be done more comfortably.

What are the methods involved in JavaScript?

- Method is an informative that gets performed over an action that is related to the object. Method either performs on some object or affect any part of the the script or a document. Object can have as many number of methods that have associations with other objects. There is a method that is used by the JavaScript statement that includes a reference to an object this is given as :
- These are the functions which perform the dynamic interaction with the user. The first statement execute the element when pressed submit button to send a form to a server. These two statements are related to only the form. The scripts that are invoked will have the write of the document as well and will be written as :
document.write(“Give the version “ + navigator.appVersion)
document.write(“ of <B>” + navigator.appName + “</B>.”)

Explain with an example the use of event handlers in JavaScript.

The events in JavaScript are the actions in a document that result from user activity. The actions are like clicking on a button or typing a character in the form. JavaScript object in a document that receives events of different kinds. To handle the events that are taking place requires an even handler that can handle the execution of the events. Event acts like an added attribute that is entered in object’s HTML. The attribute is consisting of event name, sign like (=), instructions. The following code shows the event handler as :
<INPUT TYPE=”button” VALUE=”Hello” onClick=”window.alert (‘HELLO WORLD’)”>

How are tag positions used in JavaScript?

- The tag can be inserted in a document wherever there is a requirement for a tag to be put. Nested tags are also possible within a <HEAD>...</HEAD> tag. There are many other ways to use the tag like inside <BODY>...</BODY> section.
- The tags can be placed inside <SCRIPT> tag also. The position of a particular tag is not fixed and it can be placed anywhere in the HTML document. Head is a used to place the tags that consists of noncontent settings.
- The example will show the position of <SCRIPT> tag :
<TITLE>Tag position</TITLE>
<SCRIPT LANGUAGE=”Text/JavaScript”>
// your script statement(s) here
- This uses the <SCRIPT> tag inside the HEAD section.
- There is one more code that will show the positon of <SCRIPT> in body section and it is as :
<TITLE>Tag position</TITLE>
<SCRIPT LANGUAGE=”Text/JavaScript”>
// your script statement(s) here

What are the main functions performed by JavaScript Statements?

The <SCRIPT> Script statement(s) </SCRIPT> tag consists of JavaScript statement. Just to be compatible with all the browsers it is been written in comments and it also accepts a semicolon(;) at the end of every statement. JavaScript also uses the carriage return at the end of a statement. Every statement has a purpose like:
- Define or initialize a variable that will be used in an object when executing the script
- Assign a value to a property or variable so that user inputs can be taken according to the values that are defined in it.
- Change the value of a property or variable to give more flexibility to the use of a scripting language.
- Invoke an object’s method to allow faster processing of the system
- Invoke a function routine to allow the function to perform various activities so that the application can run at faster speed.

Explain the process of document loading.

When a document loads that means it is getting ready for the execution on the system. The document loads in the browser when there is a running of a document on the system. The applicaiton allows the JavaScript to look for all the properties that is given to the object and include all the property values that are used in the content that is being rendered for the page about to load. It is always a good practice to include the content in <SCRIPT> tags and statements in the Body portion of the document. This way the application gets loaded immediately.
<TITLE>Immediate loading</TITLE>
<H1>JavaScript used</H1>
<SCRIPT LANGUAGE=”Text/JavaScript”>
<!-- Comments are used to hide from old browsers
document.write(“Give the version “ + navigator.appVersion)
document.write(“ of <B>” + navigator.appName + “</B>.”)
// end of the comment section -->

What is the function of Deferred scripts?

Deferred scripts are the scripts whose statements run as grouped together statements as a function. Function provides a definition of a block that a script statement consists of to run the statements that are in the <SCRIPT> tags after all the statements loaded in the browser. Functions allow to see the user clearly the visiblity inside the <SCRIPT> tag. In this tag each function starts with function() and function name is written after it including the parentheses. Once a function is loaded it becomes ready to run whenever there is a use of it. It is useful when a function gets used immediately after a page load. The Window object uses an event handler that triggers the response to the user actions and the handler is onLoad.

Write a program to exaplain the deferred scripts using event handlers in JavaScript.

Event handler allows a trigger to be generated when a user action takes place like clicking a button, clicking on images, etc. OnLoad is an event handlers that handles all of the page's components that includes images, Java applets, and embedded multimedia to laod it in browser. The event handlers are mostly used in <BODY> tag. Event handler is also used to run several internal script statements such that it is better to use statements in a function definition and event handler invoking the function. The code below shows onLoad event handler triggers the done() function. The function consists of an alert box that gets displayed.
<SCRIPT LANGUAGE=”Text/JavaScript”>
function done()
   alert(“The page has finished loading.”)
// -->
<BODY Event_handler=”done()”>

What is the difference between Scripting and Programming?

- Scripting is easier to write than programming. As programming requires more hands on to the code and a language specification to write.
- Scripting consists of lots of tools to easily create an object model and run it using any browser, wheras programming doesn't have many tools to create an object model and it is not easy to use browser compatibility.
- Scripts work with more than just objects, each statement of the JavaScript does something means perform some actions, whereas programming becomes different as each and every action takes time to execute.
- Scriptting doesn't require lots of knowledge to be provided with and can be easily learnt, but to learn a programming language it requires lots of knowledge.

What does dynamic component in JavaScript contain?

Dynamic component is a model that consists of many other sub-components that are based on dynamic theory only like:
Dynamic typing :
These are associated with the values and not having any association with the variables. JavaScript support the use of many types that can be used as an object.
Object based :
JavaScript is an object-oriented language and it deals with the objects that are associated arrays used with prototypes. The properties of the object based component can be modified, removed or added at run-time. The properties are using built in functions that helps to keep the property of dynamicity of the application.
Run-time evaluation :
JavaScript provides a run time evaluation using the eval() that takes some arguments provided during run time. This evaluation is used to make the scripting language more widely used as run time evaluation slows down the system but JavaScript uses the libraries to take less space.

What are the different functional component in JavaScript?

The different components that are required in the functional model is :
First-class functions :
Fuctions that are first class will have some objects whose properties and methods are given by using the methods like length() and call(). These methods can be given different varibles and passed by an argumnent.
Nested functions :
These are the functions that are used in another function. It is created each time the outer function is invoked. If a function is used inside another then any constants, local variables and argument values, become part of the function object.
Closures :
JavaScript allows the function to be created with nested functionality. It usually try to find the combination of code that can be used to execute the application.

What is the difference between script type and the script language attributes?

- The script type specifies the type of content that is used to show the language used by the browsers like “language=text/javascript”. This defines the MIME type that is also known as Multipurpose Internet Mail Extensions (MIME). Text in this defines a plain text format and script defines the language that will be used.
- The script language attribute on the other hand specify a particular version of JavaScript language that is required to run the script and to provide a mechanism to fall back if any browser doesn't support it.
- Script type is used to define the type through which the browser can understand the language and all the compatible browsers can execute the type according to themselves, whereas the script language attribute defines the content and its attributes that are used.

What are the different types of errors supported by JavaScript?

There are many errors that can occur in a system. JavaScript provides a message for all the errors at run time and dynamically generate the error code. The errors that are present :
Load-time errors :
These are the errors that come when loading a web page like using of improper syntax and the errors gets detected the moment user loads a page.
Run-time errors :
These are the errors that comes due to misuse of the language commands used inside the HTML document. This shows that it has loaded but the functionality is not properly integrated.
Logic errors :
These are the errors that comes due to bad logic performed on a function that is having different operation but it is made to have logic differently.

What are Math Constants and Functions using JavaScript?

- Math object has two constant : Math.PI and Math.E
- Math object has following functions :
Math.abs(val1); :It will give absolute value of val1.
Math.max(val1,val2); :This fuction will return maximum value from val1 and val2.
Math.random(); :This function will return a random number between 0 and 1.
Math.floor(val1) :This function will returns decimal value of val1.

What is Pop() method in JavaScript?

- The pop() method is similar as the shift() method but the difference is that Shift method works at the end of the array.
- The pop() method take the last element off of the given array and returns it. The array on which is called is then altered.
- For example :
var fruits = ["apple ", "banana ", "mango"];
console.log(fruits.pop() );
- We get the following console output :
["apple ", "banana “];

What is difference between undefined variable and undeclared variable?

- The variable which are declared in the program but not assigned any value yet is called undefined variable while the variable which are not declared in the program is called undeclared variable.
- For Example :
undeclared variable:
var p;
alert(p); // This will give error because p is undeclared variable.
? undefined variable
alert(p); //This will give error because p is undefined.

How to create an array in JavaScript?

- We can create an array in JavaScript as following ways :
- For example :
var fruits = new Array[];
fruits[0] = “Apple”;
fruits[1] = “Orange”;
fruits[2] = “Banana”;
- It will give output : Orange
- Another easier way to create an array is as follow :
var fruits = [“Apple”,”Orange”,”Banana”];
- This will give output : Apple

What is encodeURI() function?

- encodeURI() function is used to encode the URI.
- This function does not encode following special characters :
' = , ? : $ @ / & # + '
- Syntax : encodeURI(uri), Where uri is URI to be encoded.
- For example :
var uri = “EmpDetails.asp?Emp=årpit&mode=edit”;
document.write(encodeURI(uri) + “<br/>”);
Output :

Can you explain about Screen object?

- The screen object can be used to retrieve the information about the visitor’s screen.
- There are following properties of Screen objects :
avalHeight : This property returns the height of the screen excluding the windows taskbar.
availWidth : This property returns the width of the screen excluding the windows taskbar.
colorDepth : This property returns the bit depth of the color palette to display images.
height : This property returns the total height of the screen.
pixelDepth : This property returns the color resolution of the screen in bits per pixel.
width : This property returns the total width of the screen.

What is unshift() method in Javascript?

- The unshift() method is like the push() method, only it works at the beginning of the array. The unshift() method can prepend one or more elements to the beginning of an array. This alters the array on which the method was called.
- For example :
var fruits = [ "apple" ];
fruits.unshift( "banana" );
fruits.unshift( "mango", "strawberry" );
- We get the following console output :
["mango ", " strawberry ", " banana ", " apple "]

What is unescape() function?

- The unescape() function is used to decode the encoded string.
- Syntax : unescape(string1)
- Where string1 is the string to be decoded.
- Example :
- Output :
Questions? Get from us!

How to get height and width of different browser in Javascript?

Following examples illustrate the different ways to get height and width of different browser.
For Non-IE :
var Width;
var Height;
Width = window.innerWidth;
Height = window.innerHeight;
For IE 6+ in standards compliant mode :
Width = document.documentElement.clientWidth;
Height = document.documentElement.clientHeight;
For IE 4 compatible :
Width = document.body.clientWidth;
Height = document.body.clientHeight;

What is the disadvantages using innerHTML in JavaScript?

- If you use innerHTML the content is replaced everytime.
- We cannot use like 'appending to innerHTML'.
- Even if we use += like "innerHTML = innerHTML + ‘html’" then also the old content is replaced by html.
- If we use innerHTML then the entire innerHTML content is re-parsed and build into elements. Therefore it’s much slower.
- The innerHTML doesn't provide validation and therefore we can potentially insert invalid and broken HTML in the document and break it.

What is Push() method in JavaScript?

- The push() method is used to append one or more elements to the end of an array.
- For example :
var fruits = [ "apple" ];
fruits.push( "banana" );
fruits.push( "mango", "strawberry” );
- We get the following console output :
["apple ", "banana ", "mango ", "strawberry "]
- Using Push() method we can also append multiple elements by passing multiple arguments.
- The elements will be appended in the order of they are inserted i.e. left to right.

Explain JavaScript closures by example.

-The closure is a local variable of a function which remains alive after the function has returned.
-Closure combines a function with a local variable available at the time of creating closure.
- For example :
function wish(msg)
function greeting(name, occasion)
   return name + ", Happy " + occasion;
var message = greeting ("Arpit", “Birthday”);
// Pass it explicitly to wish
- By using closure we can simplify above code.
function greeting (name, occasion)
   var msg = name + ", Happy " + occasion;
   return function wish()
// create the closure
var wisharpit = greeting ("Arpit", “Birthday”);

// use the closure
wisharpit ();
- Here wish function is nested within the greeting, so closure can access the local variable of greeting which are name, occasion and msg.

What is Strict Mode in JavaScript?

-The fifth edition of ECMAScript specification has introduced Script Mode.
-Strict Mode applies a layer of constraint on JavaScript.
-It throws errors for actions that are problematic and didn’t throw an error before.
-It throws errors for the actions which are potentially unsafe.
-It shut downs the functions which are poorly thought out.
-Strict mode solves mistakes that are responsible for the difficulty of JavaScript engines to perform optimizations.
-To enable the strict mode we have to add the string literal “use strict” on the top of file or function as follow :
function myfunction()
   “use strict";
   var v = “I am a strict mode function";

How to create an array in Javascript?

- To create an array in Javascript we have declare the array variable.
- For example :
var fruits = new Array()
- We can add elements in this array as below :
fruits[0] = “banana”’
fruits[1] = “apple”
fruits[2] = “mango”
- We can get each elements of fruit array with the index number of element where index number starts from 0.
- If we want to get the second element of fruit array then we have to use index number 1 as below :
- We also can create an array as below :
var mynos = new Array(1,2,3,4,5)

What is decodeURI() function?

- The decodeURI() function is used to decode the URI.
- Syntax :
Where uri is URI to be decoded
- For example :
var uri = “EmpDetails.asp?Emp=årpit&mode=edit”;
document.write(encodeURI(uri) + “<br/>”);
document.write(decodeURI(uri) + “<br/>”);
- Output :

What is the difference between window.onload and onDocumentReady?

- The difference is that onDocumentReady is called after the DOM is loaded without waiting for all the contents to get loaded. While window.onload() function waits until the contents of page is loaded.
- Suppose there is very large image on a page, at that time onDocumentReady will wait until that image is loaded totally.
- So while using the window.onlaod() function the execution will be slow, but the onDocumentReady will not wait until the image is loaded.

How to manage exception handling in Javascript?

- Javascript provides the features of exception handling using try..catch..finally blocks which is much similar to the C# exception handling blocks.
- We have to write the suspected code in try block and all the exceptions that occur in the try block will be caught in catch block.
- For example :
window.onload = function()
       var v1=30;
       var v2 =v1/v3;
       document.write(ex.name + “ : ” +ex.message);
       document.write(‘this is finally block’);
- This code snippet will cause an error :
TypeError : ‘v3’ is undefined.

How to change style on an element?

- If we want to change only a single property of an element’s style, we can change the CSS of element using the element's style property :
var myelement = document.getElementById("mydiv");
myelement.style.width = "200px";
- If we want to change value of more than one properties, we can use the element’s setAttribute method :
myelement.setAttribute("style","width: 200px; background-color: blue;");
- If the CSS property contains a hyphen, for example” font-family” or “background-color”, we have to use CamelCase notation as follows :
myelement.style.fontFamily = "Arial";
myelement.style.backgroundColor = "rgb(255,222,12)";
- We can also use the element’s setAttribute method to set the style property :
myelement.setAttribute("style","font-family: Arial; background-color: green");

What is escape() function?

- The escape() function is used to encode the string to convert it as portable string so that it can be sent across any network to any computer which supports ASCII characters.
-This function encodes special characters, with the exception of @ * + - / . _
- Syntax :
Where string1 is the string to be encoded.
- Example :
document.write(escape(“Questions? Get from us!”));
- Output :

What is Shift() method in Javascript?

-The shift() method is similar as the pop() method but the difference is that Shift method works at the beginning of the array.
-The shift() method take the first element off of the given array and returns it. The array on which is called is then altered.
- For example :
var myarray = ["apple ", "banana ", "mango "];
- We get the following console output :
["banana ", "mango "];
- When we call shift() on an empty array, it will return an undefined value.
JavaScript vs. Jscript
Both JavaScript and Jscript are almost similar. Java script was developed by Netscape...
Difference between Client side JavaScript and Server side JavaScript
difference between Client side JavaScript and Server side JavaScript - ...
JavaScript - Where are cookies actually stored on the hard disk?
Where are cookies actually stored on the hard disk? - ...
Post your comment
Discussion Board
Javascript interview questions and answers
Are there any predefined constant provided by the browser with the key code values that can be reused?
Use of global object, named as KeyEvent object, used in firefox browser, providing set of pre-defined constants that reflect the keys, which are used on keyboards. The constant’s name used is: DOM_VK_KEYNAME, with values representing the keydown/keyup key codes for the respective keys. For example, DOM_VK_SHIFT is 16, DOM_VK_ESCAPE is 27.

How can I set up my own JavaScript error handler?
To set up your own JavaScript error handler some optional parameters has to be known. These parameters are as follows:
- Textual description of error
- Address (URL) of page on which error occurred
- Number of line in which error occurred
If you want to invoke the default error handler of the browser, then your function should return (false) or vice versa. Example code:
function handlerFunction(description,page,line)
{ // put error-handling operators here
return true;}

How do I use JavaScript to password-protect my Web site?
There are several ways in which you can use JavaScript to password-protect your website. This can be done by setting the password by using the given name or pathname of HTML file on your site. Set the location to value entered in the field. Entry of wrong password will result in “invalid URL” error. If password protect pages requires more security then you can set temporary cookies on the page.

How can I prevent others from reading/stealing my scripts or images?
There are no assertive measures which can be taken to foolproof your scripts and images, but preventive measures can be taken like copyrighting your pages, putting watermark on your images and applying non-technological way to protect your images. Scripts are difficult to protect as they can be accessed through many applications and many programs by using the web browsers.
Rohit Sharma 12-11-2011
JavaScript interview questions and answers
How do I write script-generated content to another window?
You can use the methods winRef.document.writeln() or winRef.document.write() to write the script-generated content to another window. winRef stands for windows reference, it is being returned by window.open() method. Use of winRef.document.close() can be used if you want your script’s output to show up. Example code:
writeConsole('Hello world!');
function writeConsole(content) {
top.consoleRef=window.open('','myconsole', 'width=350,height=250'
top.consoleRef.document.writeln( '<html><head><title>Console</title></head>' +' top.consoleRef.document.close() }

How can I request data from the server without reloading the page in the browser?
JavaScript code which is being present and loaded in client browser, can request for data from the web server using XMLHttpRequest object. XMLHttpRequest.open() method is used to open the connection, not to send the request to web server. But, use of the function XMLHttpRequest.send() sends the request in real time. Example code is given below as:
var oRequest = new XMLHttpRequest();
var sURL = "http://"+ self.location.hostname + "/hello/requested_file.htm";
if (oRequest.status==200) alert(oRequest.responseText);
else alert("Error executing XMLHttpRequest call!");

How do I add a JavaScript event handler to an HTML page element?
You can use inline event handlers to add a JavaScript handler to an HTML page element. The disadvantage of this technique is that it allows you to have one handler per element. There are different browsers which allow you to have dynamic handler added to the HTML page element. Example of inline event handler is given below:
<a href="ineh.htm" onlick="alert('Hello!')">Good Morning!</a>
// event handlers added by assignment (usually right after the page loads), e.g.:

Rohit Sharma 12-11-2011
JavaScript interview questions and answers
How do I retrieve a cookie with a given name using a regular expression?
You can use readCookie() function to read the cookie. It provides sufficient arguments that one can find it, flexible to use. It takes cookieName as a parameter and other statements in the block. Below function uses the cookie function as well as regular expression to show the functionality:
function readCookie(cookieName)
{ var rx = new RegExp('[; ]'+cookieName+'=([^\\s;]*)');
var sMatch = (' '+document.cookie).match(rx);
if (cookieName && sMatch) return unescape(sMatch[1]);
return '';

What value does prompt() return if the user clicked the Cancel button?
Return value of prompt() function depends on browsers. Most of the browsers return the value as null and some return as empty string (“ “). IE is one of the browser which gives the error of empty string when clicked the cancel button by the user, otherwise all the recent browser return the value as null. The code to check this is as follows:
userInput = prompt('Prompt text','Suggested input');
if (userInput) {
// do something with the input

Why does the browser display the slow script warning?
When JavaScript on your browser is running but, it is not responding from a long time, then browser may display a warning message and give the user an option to terminate the script. Example, while loading a video application on Internet Explorer 8.0, it displays Yes/No dialog message like this:
Stop running this script?
A script on this page is causing Internet Explorer to run slowly.
If it continues to run, your computer might become unresponsive.
Rohit Sharma 12-11-2011