1. Can you use x === "object" to test if x is an object?

In short, yes, but you must take into account the fact that null is considered an object in JavaScript. Even if x is null, 'console.log(typeof x === "object")' will log true instead of false.
To account for this, you must also test whether or not x is null by including the following:
console.log((x !== null) && (typeof x === "object"));

2. What happens when you don't declare a variable in Javascript?

If you don't explicitly declare a variable, you risk creating an implied global variable. This is a problem, as you will be unable to create multiple instances of that object, as each new instance will overwrite the data from the last.
In general, global variables should be used only in very specific situations and are typically not recommended, as they can lead to a lot of odd side effects that may be difficult to track down.

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

4. Explain the concept of unobtrusive JavaScript?

Unobtrusive JavaScript is basically a JavaScript methodology that seeks to overcome browser inconsistencies by separating page functionality from structure. The basic premise of unobtrusive JavaScript is that page functionality should be maintained even when JavaScript is unavailable on a user's browser.

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

6. What is namespacing in JavaScript and how is it used?

Namespacing is used for grouping the desired functions, variables etc. under a unique name. It is a name that has been attached to the desired functions, objects and properties. This improves modularity in the coding and enables code reuse.

7. What is NaN in JavaScript?

Nan is literally "Not-a-Number". NaN usually results when either the result or one of the values in an operation is non-numeric. Even though NaN is not a number, 'console.log(typeof NaN === "number");' logs true, while NaN compared to anything else (including NaN) logs false. The only real way to test if a value is equal to NaN is with the function 'isNaN()'.

8. 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 :
<script>
document.write(unescape("Questions%3F%20Get%20from%20us%21"));
</script>
- Output :
Questions? Get from us!

9. How are JavaScript and ECMA Script related?

ECMAScript is nothing but another name for JavaScript. Precisely, ECMAScript is the formal name of JavaScript, when XML elements have to be accessed.

10. Which boolean operators are in JavaScript?

'and' operator: &&
'or' operator: ||
'not' operator: !

Download Interview PDF

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

12. What is the method for reading and writing a file in JavaScript?

This can be done by Using JavaScript extensions (runs from JavaScript Editor), example for opening of a file -

fh = fopen(getScriptPath(), 0);

13. Is JavaScript case sensitive?

Yes, absolutely. For example, the function getElementById is not the same as the function getElementbyID. Keeping your capitalization consistent is important.

14. What is 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.

15. How can a particular frame be targeted, from a hyperlink, in JavaScript?

This can be done by including the name of the required frame in the hyperlink using the 'target' attribute.

<a href="newpage.htm" target="newframe">>New Page</a>

16. Why would you include 'use strict' at the beginning of a JavaScript source file?

Using strict mode enforces stricter error handling when running your code. It essentially raises errors that would have otherwise failed silently. Using strict mode can help you avoid simple mistakes like creating accidental globals, undefined values, or duplicate property names. This is typically a good idea when writing JavaScript, as such errors can create a lot of frustrating side effects and be difficult to track down.

17. 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 "];
console.log(myarray.shift());
console.log(myarray);
► We get the following console output :
apple
["banana ", "mango "];
► When we call shift() on an empty array, it will return an undefined value.

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

19. What is the difference between JavaScript and JScript?

Both are almost similar. JavaScript is developed by Netscape and Jscript was developed by Microsoft.

20. What does a timer do and how would you implement one?

Setting timers allows you to execute your code at predefined times or intervals.
This can be achieved through two main methods: setInterval(); and setTimeout();
setInterval() accepts a function and a specified number of milliseconds.
ex) setInterval(function(){alert("Hello, World!"),10000) will alert the "Hello, World!" function every 10 seconds.
setTimeout() also accepts a function, followed by milliseconds. setTimeout() will only execute the function once after the specified amount of time, and will not reoccur in intervals.

21. 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" );
console.log(fruits);
► 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.

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

23. What are the different types of errors in JavaScript?

There are three types of errors:

► Load time errors: Errors which come up when loading a web page like improper syntax errors are known as Load time errors and it generates the errors dynamically.
► Run time errors: Errors that come due to misuse of the command inside the HTML language.
► Logical Errors: These are the errors that occur due to the bad logic performed on a function which is having different operation.

24. What is JavaScript, what about history?

JavaScript, some also know it as ECMAScript, is a dynamic programming language used in a web development. It is an integral part of web browsers, and it allows, among other things, better user interaction, browser control, client-server communications (synchronous and asynchronous), alterations of displayed DOM content.

Although it was first introduced under a different name (Mocha), during its initial release it was officially named LiveScript. Developed by Netscape, the first version was available in Navigator 2.0 (September 1995), but it was renamed JavaScript in version 2.0B3.

25. 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 :
escape(string1)
Where string1 is the string to be encoded.
► Example :
<script>
document.write(escape("Questions? Get from us!"));
</script>
► Output :
Questions%3F%20Get%20from%20us%21

Download Interview PDF

26. 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:
<script>
var p;
alert(p); // This will give error because p is undeclared variable.
</script>
? undefined variable
<script>
alert(p); //This will give error because p is undefined.
</script>

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;}
window.onerror=handlerFunction;

28. Explain what is pop()method in JavaScript?

The pop() method is similar as the shift() method but the difference is that the Shift method works at the start of the array. Also the pop() method take the last element off of the given array and returns it. The array on which is called is then altered.
Example:
var cloths = ["Shirt", "Pant", "TShirt"];
cloths.pop();
//Now cloth becomes Shirt,Pant

29. What is event bubbling, and why is it beneficial to use?

Event bubbling transfers events contained within the child node to the parent node. It's a beneficial method because of its speediness, as it only requires the code to traverse the DOM tree one time.

30. What would "1"+2+3 and 1+2+"3" evaluate to, respectively?

When the first character is a string, the remaining characters will be converted into a single string, rendering 123.
If the string is at the end, the initial characters will perform normal mathematical functions before converting into a string, resulting in 33.

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

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

33. How can JavaScript codes be hidden from old browsers that don't support JavaScript?

For hiding JavaScript codes from old browsers:

Add "<!-" without the quotes in the code just after the <script> tag.

Add "//->" without the quotes in the code just before the <script> tag.

Old browsers will now treat this JavaScript code as a long HTML comment. While, a browser that supports JavaScript, will take the "<!-" and "//->" as one-line comments.

34. How can a page be forced to load another page in JavaScript?

The following code has to be inserted to achieve the desired effect:

XHTML

<script language="JavaScript" type="text/javascript" >

<!-- location.href="http://newhost/newpath/newfile.html"; //--></script>

35. What does the isNaN() function do?

The isNaN() function is used to determine whether a value is not a number, or an illegal number. If the argument is not a number, the isNaN() function will return TRUE.

36. What is the difference between a null value and an undefined value?

Null is used to assign an empty value to a variable and needs to be assigned manually.
Undefined values result when you declare a variable without assigning it a value. Undefined will be the default whenever you don't explicitly assign a value.

37. What is decodeURI() function?

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

38. 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 :
<script>
var uri = "EmpDetails.asp?Emp=årpit&mode=edit";
document.write(encodeURI(uri) + "
");
</script>
Output :
EmpDetails.asp?Emp=%C3%A5&mode=edit.

39. 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.:
document.onclick=clickHandler;
document.onkeydown=keyHandler;

40. What is the role of break and continue statements?

Break statement is used to come out of the current loop while the continue statement continues the current loop with a new recurrence.

Download Interview PDF

41. What are all the types of Pop up boxes available in JavaScript?

► Alert
► Confirm and
► Prompt

42. What kind of looping functions does JavaScript support?

JavaScript supports for loops, while loops, and do-while loops, but not foreach loops.

43. What are your favorite JavaScript libraries?

This is one of those general open-ended questions interviewers love to throw out. The only correct answer here is one that shows you're familiar with and have an opinion on the various JavaScript libraries. You could discuss the pros and cons of using raw JavaScript vs. jQuery, or describe an instance in which you'd use one library over another. Visit jsdb.io for a complete rundown.

44. What is the difference between window.onload and the jQuery $(document).ready() method?

The window.onload method occurs after all the page elements have loaded(HTML, CSS, images), which can result in a delay.
The $(document).ready() method begins to run code as soon as the Document Object Model (DOM) is loaded, which should be faster and less prone to loading errors across different browsers.

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

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

47. 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 :
<HTML>
<BODY>
<FORM>
<INPUT TYPE="button" VALUE="Hello" onClick="window.alert ('HELLO WORLD')">
</FORM>
</BODY>
</HTML>

48. Explain the role of deferred scripts in JavaScript?

By default, the parsing of the HTML code, during page loading, is paused until the script has not stopped executing. It means, if the server is slow or the script is particularly heavy, then the webpage is displayed with a delay. While using Deferred, scripts delays execution of the script till the time HTML parser is running. This reduces the loading time of web pages and they get displayed faster.

49. What is the function of delete operator?

The functionality of delete operator is used to delete all variables and objects in a program but it cannot delete variables declared with VAR keyword.

50. Which conditional statements will JavaScript support?

if statement
if - else statement
if - else if - else statement
switch statement

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

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

53. What is the way to get the status of a CheckBox?

The status can be acquired as follows -

alert(document.getElementById('checkbox1').checked);

If the CheckBox will be checked, this alert will return TRUE.

54. What do mean by NULL in JavaScript?

The NULL value is used to represent no value or no object. It implies no object or null string, no valid boolean value, no number and no array object.

55. What is the difference between == and === ?

'==' evaluates equality of the value, while '===' evaluates equality of type and value.

Download Interview PDF

56. 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()
{
try
{
var v1=30;
var v2 =v1/v3;
}
catch(ex)
{
document.write(ex.name + " : " +ex.message);
}
Finally
{
document.write('this is finally block');
}
}
► This code snippet will cause an error :
TypeError : 'v3' is undefined.

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

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

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

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

61. Why it is not advised to use innerHTML in JavaScript?

innerHTML content is refreshed every time and thus is slower. There is no scope for validation in innerHTML and, therefore, it is easier to insert rouge code in the document and, thus, make the web page unstable.

62. What Boolean operators can be used in JavaScript?

The 'And' Operator (&&), 'Or' Operator (||) and the 'Not' Operator (!) can be used in JavaScript.

*Operators are without the parenthesis.

63. What is the difference between ViewState and SessionState?

'ViewState' is specific to a page in a session.

'SessionState' is specific to user specific data that can be accessed across all pages in the web application.

64. 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)
{
console.log(msg);
}
function greeting(name, occasion)
{
return name + ", Happy " + occasion;
}
var message = greeting ("Arpit", "Birthday");
// Pass it explicitly to wish
wish(message);
► By using closure we can simplify above code.
function greeting (name, occasion)
{
var msg = name + ", Happy " + occasion;
return function wish()
{
console.log(msg);
};
}
// 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.

65. How to create an array in JavaScript?

► We can create an array in JavaScript as following ways :
► For example :
<script>
var fruits = new Array[];
fruits[0] = "Apple";
fruits[1] = "Orange";
fruits[2] = "Banana";
alert(fruits[1]);
</script>
► It will give output : Orange
► Another easier way to create an array is as follow :
<script>
var fruits = ["Apple","Orange","Banana"];
alert(fruits[0]);
</script>
► This will give output : Apple

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

67. Explain the process of document loading in JavaScript?

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.
<HTML>
<HEAD>
<TITLE>Immediate loading</TITLE>
</HEAD>
<BODY>
<H1>JavaScript used</H1>
<HR>
<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 -->
</SCRIPT>
</BODY>
</HTML>

68. 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 :
document.orderForm.submit()
document.orderForm.entry.select()
- 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>.")

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

70. How are event handlers utilized in JavaScript?

Events are the actions that result from activities, such as clicking a link or filling a form, by the user. An event handler is required to manage proper execution of all these events. Event handlers are an extra attribute of the object. This attribute includes event's name and the action taken if the event takes place.

Download Interview PDF

71. What is variable typing?

Variable typing is used to assign a number to a variable and then assign string to the same variable. Example is as follows:


i= 8;

i="Muhammad";

72. Explain the working of timers in JavaScript? Also elucidate the drawbacks of using the timer, if any?

Timers are used to execute a piece of code at a set time or also to repeat the code in a given interval of time. This is done by using the functions setTimeout, setInterval and clearInterval.

The setTimeout(function, delay) function is used to start a timer that calls a particular function after the mentioned delay. The setInterval(function, delay) function is used to repeatedly execute the given function in the mentioned delay and only halts when cancelled. The clearInterval(id) function instructs the timer to stop.

Timers are operated within a single thread, and thus events might queue up, waiting to be executed.

73. 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() );
console.log(fruits);
► We get the following console output :
mango
["apple ", "banana "];

74. 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 :
<HTML>
<HEAD>
<TITLE>Tag position</TITLE>
<SCRIPT LANGUAGE="Text/JavaScript">
// your script statement(s) here
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
► 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 :
<HTML>
<HEAD>
<TITLE>Tag position</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="Text/JavaScript">
// your script statement(s) here
</SCRIPT>
</BODY>
</HTML>

75. 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'
+',menubar=0')
top.consoleRef.document.writeln( '<html><head><title>Console</title></head>' +' top.consoleRef.document.close() }

76. What does the following statement declares?

JavaScript

var myArray = [[[]]];

It declares a three dimensional array.

77. What is the difference between an alert box and a confirmation box?

An alert box displays only one button which is the OK button.

But a Confirmation box displays two buttons namely OK and cancel.

78. Is it possible to break JavaScript Code into several lines?

Breaking within a string statement can be done by the use of a backslash, '', at the end of the first line

Example:
document.write("This is a program");

And if you change to a new line when not within a string statement, then javaScript ignores break in line.

Example:
var x=1, y=2,
z=
x+y;

The above code is perfectly fine, though not advisable as it hampers debugging.

79. 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.
<HTML>
<HEAD>
<TITLE>Event_handler</TITLE>
<SCRIPT LANGUAGE="Text/JavaScript">
<!--
function done()
{
alert("The page has finished loading.")
}
// -->
</SCRIPT>
</HEAD>
<BODY Event_handler="done()">
</BODY>
</HTML>

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

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

82. Write about the errors shown in JavaScript?

JavaScript gives a message if it encounters an error. The recognized errors are -

► Load-time errors: The errors shown at the time of the page loading are counted under Load-time errors. These errors are encountered by the use of improper syntax, and thus are detected while the page is getting loaded.
► Run-time errors: This is the error that comes up while the program is running. It is caused by illegal operations, for example, division of a number by zero, or trying to access a non-existent area of the memory.
► Logic errors: It is caused by the use of syntactically correct code, which does not fulfill the required task. For example, an infinite loop.

83. Describe the properties of an anonymous function in JavaScript?

A function that is declared without any named identifier is known as an anonymous function. In general, an anonymous function is inaccessible after its declaration.

Anonymous function declaration -

var anon = function() {
alert('I am anonymous');
};

anon();

84. What is the use of blur function?

Blur function is used to remove the focus from the specified object.

85. What are all the looping structures in JavaScript?

Following are looping structures in Javascript:

► For
► While
► do-while loops

Download Interview PDF

86. Tell me what is negative infinity?

Negative Infinity is a number in JavaScript which can be derived by dividing negative number by zero.

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

88. 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";
oRequest.open("GET",sURL,false);
oRequest.setRequestHeader("User-Agent",navigator.userAgent);
oRequest.send(null)
if (oRequest.status==200) alert(oRequest.responseText);
else alert("Error executing XMLHttpRequest call!");

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

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

91. What are Screen objects in JavaScript?

Screen objects are used to read the information from the client's screen. The properties of screen objects are -

► AvalHeight: Gives the height of client's screen
► AvailWidth: Gives the width of client's screen.
► ColorDepth: Gives the bit depth of images on the client's screen
► Height: Gives the total height of the client's screen, including the taskbar
► Width: Gives the total width of the client's screen, including the taskbar

92. Write the point of difference between web-garden and a web-farm?

Both web-garden and web-farm are web hosting systems. The only difference is that web-garden is a setup that includes many processors in a single server while web-farm is a larger setup that uses more than one server.

93. What is the 'Strict' mode in JavaScript and how can it be enabled?

Strict Mode adds certain compulsions to JavaScript. Under the strict mode, JavaScript shows errors for a piece of codes, which did not show an error before, but might be problematic and potentially unsafe. Strict mode also solves some mistakes that hamper the JavaScript engines to work efficiently.

Strict mode can be enabled by adding the string literal "use strict" above the file. This can be illustrated by the given example:

JavaScript

function myfunction()
{
"use strict";
var v = "This is a strict mode function";
}

94. What are the two basic groups of dataypes in JavaScript?

They are as -
► Primitive
► Reference types.

Primitive types are number and Boolean data types. Reference types are more complex types like strings and dates.

95. Explain how can you submit a form using JavaScript?

To submit a form using JavaScript use document.form[0].submit();

document.form[0].submit();

96. Between JavaScript and an ASP script, which is faster?

JavaScript is faster. JavaScript is a client-side language and thus it does not need the assistance of the web server to execute. On the other hand, ASP is a server-side language and hence is always slower than JavaScript.

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

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

<HTML>
<HEAD>
<!--
<SCRIPT> // Starting of the scripting language
//Your code here
</SCRIPT> --> // End of the scripting language
</HEAD>
<BODY>
// your code here
</BODY>
</HTML>

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

100. Define unescape() and escape() functions?

The escape () function is responsible for coding a string so as to make the transfer of the information from one computer to the other, across a network.

For Example:

<script>
document.write(escape("Hello? How are you!"));
</script>

Output: Hello%3F%20How%20are%20you%21

The unescape() function is very important as it decodes the coded string.

It works in the following way. For example:

<script>
document.write(unescape("Hello%3F%20How%20are%20you%21"));
</script>

Output: Hello? How are you!

Download Interview PDF

101. How are DOM utilized in JavaScript?

DOM stands for Document Object Model and is responsible for how various objects in a document interact with each other. DOM is required for developing web pages, which includes objects like paragraph, links, etc. These objects can be operated to include actions like add or delete. DOM is also required to add extra capabilities to a web page. On top of that, the use of API gives an advantage over other existing models.

102. What is the difference between .call() and .apply()?

The function .call() and .apply() are very similar in their usage except a little difference. .call() is used when the number of the function's arguments are known to the programmer, as they have to be mentioned as arguments in the call statement. On the other hand, .apply() is used when the number is not known. The function .apply() expects the argument to be an array.

The basic difference between .call() and .apply() is in the way arguments are passed to the function. Their usage can be illustrated by the given example.

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

103. Explain the for-in loop?

The for-in loop is used to loop through the properties of an object.

The syntax for the for-in loop is -

for (variable name in object){
statement or block to execute
}

In each repetition, one property from the object is associated to the variable name, and the loop is continued till all the properties of the object are depleted.

104. What is the use of Push method in JavaScript?

The push method is used to add or append one or more elements to the end of an Array. Using this method, we can append multiple elements by passing multiple arguments

105. What is break and continue statements?

Break statement exits from the current loop.

Continue statement continues with next statement of the loop.

106. What is called Variable typing in Javascript?

Variable typing is used to assign a number to a variable and the same variable can be assigned to a string.

Example

i = 10;

i = "string";

This is called variable typing.

107. What are global variables? How are these variable declared and what are the problems associated with using them?

Global variables are those that are available throughout the length of the code, that is, these have no scope. The var keyword is used to declare a local variable or object. If the var keyword is omitted, a global variable is declared.

Example:
// Declare a global globalVariable = "Test";

The problems that are faced by using global variables are the clash of variable names of local and global scope. Also, it is difficult to debug and test the code that relies on global variables.

108. Enumerate the differences between Java and JavaScript?

Java is a complete programming language. In contrast, JavaScript is a coded program that can be introduced to HTML pages. These two languages are not at all inter-dependent and are designed for the different intent. Java is an object - oriented programming (OOPS) or structured programming language like C++ or C whereas JavaScript is a client-side scripting language and it is said to be unstructured programming.

109. What are the decodeURI() and encodeURI()?

EncodeURl() is used to convert URL into their hex coding. And DecodeURI() is used to convert the encoded URL back to normal.

<script>
var uri="my test.asp?name=ståle&car=saab";
document.write(encodeURI(uri)+ "
");
document.write(decodeURI(uri));
</script>

Output -
my%20test.asp?name=st%C3%A5le&car=saab
my test.asp?name=ståle&car=saab

110. Explain the unshift() method in JavaScript?

This method is functional at the starting of the array, unlike the push(). It adds the desired number of elements to the top of an array. For example -


var name = [ "john" ];
name.unshift( "charlie" );
name.unshift( "joseph", "Jane" );

console.log(name);

The output is shown below:

[" Jane ", " joseph ", " charlie ", " john "]

111. What are the various functional components in JavaScript?

The different functional components in JavaScript are-

First-class functions:
Functions in JavaScript are utilized as first class objects. This usually means that these functions can be passed as arguments to other functions, returned as values from other functions, assigned to variables or can also be stored in data structures.

Nested functions:
The functions, which are defined inside other functions, are called Nested functions. They are called 'everytime' the main function is invoked.

112. How are object properties assigned in JavaScript?

Assigning properties to objects is done in the same way as a value is assigned to a variable. For example, a form object's action value is assigned as 'submit' in the following manner - Document.form.action="submit"

113. Is JavaScript case sensitive? Give an example?

Yes, JavaScript is case sensitive. For example, a function parseInt is not same as the function Parseint.

114. How will you explain closures in JavaScript? When are they used?

Closure is a locally declared variable related to a function which stays in memory when the function has returned.

For example:

JavaScript

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

115. Explain window.onload and onDocumentReady?

The onload function is not run until all the information on the page is loaded. This leads to a substantial delay before any code is executed.

onDocumentReady loads the code just after the DOM is loaded. This allows early manipulation of the code.

Download Interview PDF

116. What is unshift method in JavaScript?

Unshift method is like push method which works at the beginning of the array. This method is used to prepend one or more elements to the beginning of the array.

117. Which keywords are used to handle exceptions?

Try… Catch-finally is used to handle exceptions in the JavaScript

JavaScript

Try{
Code
}
Catch(exp){
Code to throw an exception
}
Finally{
Code runs either it finishes successfully or after catch
}

118. What are JavaScript Cookies?

Cookies are the small test files stored in a computer and it gets created when the user visits the websites to store information that they need. Example could be User Name details and shopping cart information from the previous visits.

119. Explain the difference between "==" and "==="?

"==" checks only for equality in value whereas "===" is a stricter equality test and returns false if either the value or the type of the two variables are different.

120. Explain how to read and write a file using JavaScript?

There are two ways to read and write a file using JavaScript

► Using JavaScript extensions
► Using a web page and Active X objects

121. What is 'this' keyword in JavaScript?

'This' keyword is used to point at the current object in the code. For instance: If the code is presently at an object created by the help of the 'new' keyword, then 'this' keyword will point to the object being created.

122. What is a potential pitfall with using typeof bar === "object" to determine if bar is an object? How can this pitfall be avoided?

Although typeof bar === "object" is a reliable way of checking if bar is an object, the surprising gotcha in JavaScript is that null is also considered an object!

Therefore, the following code will, to the surprise of most developers, log true (not false) to the console:

var bar = null;
console.log(typeof bar === "object"); // logs true!
As long as one is aware of this, the problem can easily be avoided by also checking if bar is null:

console.log((bar !== null) && (typeof bar === "object")); // logs false
To be entirely thorough in our answer, there are two other things worth noting:

First, the above solution will return false if bar is a function. In most cases, this is the desired behavior, but in situations where you want to also return true for functions, you could amend the above solution to be:

console.log((bar !== null) && ((typeof bar === "object") || (typeof bar === "function")));
Second, the above solution will return true if bar is an array (e.g., if var bar = [];). In most cases, this is the desired behavior, since arrays are indeed objects, but in situations where you want to also false for arrays, you could amend the above solution to be:

console.log((bar !== null) && (typeof bar === "object") && (toString.call(bar) !== "[object Array]"));
Or, if you're using jQuery:

console.log((bar !== null) && (typeof bar === "object") && (! $.isArray(bar)));

123. Define event bubbling in JavaScript?

JavaScript allows DOM elements to be nested inside each other. In such a case, if the handler of the child is clicked, the handler of parent will also work as if it were clicked too.

124. How can a value be appended to an array?

A value can be appended to an array in the given manner -

arr[arr.length] = value;

125. How can the OS of the client machine be detected?

The navigator.appVersion string can be used to detect the operating system on the client machine.

126. Which keyword is used to print the text in the screen?

document.write("Welcome") is used to print the text - Welcome in the screen.

127. Mention what is the disadvantage of using innerHTML in JavaScript?

If you use innerHTML in JavaScript the disadvantage is

► Content is replaced everywhere
► We cannot use like "appending to innerHTML"
► Even if you use +=like "innerHTML = innerHTML + 'html'" still the old content is replaced by html
► The entire innerHTML content is re-parsed and build into elements, therefore its much slower
► The innerHTML does not provide validation and therefore we can potentially insert valid and broken HTML in the document and break it

128. What is the use of Void(0)?

Void(0) is used to prevent the page from refreshing and parameter "zero" is passed while calling.

Void(0) is used to call another method without refreshing the page.

129. How can you convert the string of any base to integer in JavaScript?

The parseInt() function is used to convert numbers between different bases. parseInt() takes the string to be converted as its first parameter, and the second parameter is the base of the given string.

In order to convert 4F (of base 16) to integer, the code used will be -

parseInt ("4F", 16);

130. Does JavaScript support automatic type conversion?

Yes JavaScript does support automatic type conversion, it is the common way of type conversion used by JavaScript developers

Download Interview PDF

131. What are undeclared and undefined variables?

Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered.

Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.

132. What are JavaScript types?

Following are the JavaScript types:

Number
String
Boolean
Function
Object
Null
Undefined

133. How are object properties assigned?

Properties are assigned to objects in the following way -

obj["class"] = 12;

or

obj.class = 12;

134. How to find operating system in the client machine using JavaScript?

The 'Navigator.appversion' is used to find the name of the operating system in the client machine.

135. How generic objects can be created?

Generic objects can be created as:


var I = new object();

136. Whether JavaScript has concept level scope?

No. JavaScript does not have concept level scope. The variable declared inside the function has scope inside the function.

137. What is the data type of variables in JavaScript?

All variables in the JavaScript are object data types.

138. Explain how to detect the operating system on the client machine?

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

139. How can the style/class of an element be changed?

It can be done in the following way:

JavaScript

document.getElementById("myText").style.fontSize = "20?;
or
document.getElementById("myText").className = "anyclass";

140. Write the code for adding new elements dynamically?

<html>
<head> <title>t1</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>

141. Tell me what is JavaScript?

JavaScript is a client-side scripting language that can be inserted into HTML pages and is understood by web browsers.

142. What is the use of type of operator?

'Typeof' is an operator which is used to return a string description of the type of a variable.

143. What are escape characters?

Escape characters (Backslash) is used when working with special characters like single quotes, double quotes, apostrophes and ampersands. Place backslash before the characters to make it display.

Example:

document.write "I m a "good" boy"

document.write "I m a "good" boy"

144. What is an undefined value in JavaScript?

Undefined value means the

► Variable used in the code doesn't exist
► Variable is not assigned to any value
► Property doesn't exist

145. What would be the result of 3+2+"7″?

Since 3 and 2 are integers, they will be added numerically. And since 7 is a string, its concatenation will be done. So the result would be 57.

Download Interview PDF

146. What is === operator in JavaScript?

=== is called as strict equality operator which returns true when the two operands are having the same value without any type conversion.

147. Which symbol is used for comments in Javascript?

// for Single line comments and

/* Multi

Line

Comment

*/

148. What is a prompt box in JavaScript?

A prompt box is a box which allows the user to enter input by providing a text box. Label and box will be provided to enter the text or number.

149. Which company developed JavaScript?

Netscape is the software company who developed JavaScript.

150. What is the use of isNaN function?

isNan function returns true if the argument is not a number otherwise it is false.