javaScript iterview Questions

advertisement
Introduction
Below is the list of latest and updated JavaScript interview questions and their answers for freshers as
well as experienced users. These interview questions will help you to prepare for the interviews, So
let's start....
JavaScript Interview Questions for both Experienced Programmers and
Freshers
1) What is JavaScript?
Ans:JavaScript is a scripting language most often used for client-side web development.
2) What is the difference between JavaScript and Jscript?
Ans:Both JavaScript and Jscript are almost similar. JavaScript was developed by Netscape. Microsoft
reverse engineered Javascript and called it JScript.
3) How do we add JavaScript onto a web page?
Ans:There are several way for adding JavaScript on a web page, but there are two ways which are
commonly used by developers
If your script code is very short and only for single page, then following ways are the best:
a) You can place <script type="text/javascript"> tag inside the <head> element.
Code
Collapse | Copy Code
<head>
<title>Page Title</title>
<script language="JavaScript" type="text/javascript">
var name = "Vikas Ahlawta"
alert(name);
</script>
</head>
b) If your script code is very large, then you can make a JavaScript file and add its path in the
following way:
Code
Collapse | Copy Code
<head>
<title>Page Title</title>
<script type="text/javascript" src="myjavascript.js"></script>
</head>
4) Is JavaScript case sensitive?
Ans:Yes!
A function getElementById is not the same as getElementbyID.
5) What are the types used in JavaScript?
Ans:String, Number, Boolean, Function, Object, Null, Undefined.
6) What are the boolean operators supported by JavaScript? And Operator: &&
Or Operator: ||
Not Operator: !
7) What is the difference between “==” and “===”?
Ans:
“==” checks equality only,
“===” checks for equality as well as the type.
8) How to access the value of a textbox using JavaScript?
Ans: ex:Code
Collapse | Copy Code
<!DOCTYPE html>
<html>
<body>
Full name: <input type="text" id="txtFullName"
name="FirstName" value="Vikas Ahlawat">
</body>
</html>
There are following ways to access the value of the above textbox:
Collapse | Copy Code
var name = document.getElementById('txtFullName').value;
alert(name);
or:
we can use the old way:
Collapse | Copy Code
document.forms[0].mybutton.
var name = document.forms[0].FirstName.value;
alert(name);
Note: This uses the "name" attribute of the element to locate it.
9) What are the ways of making comments in JavaScript?
Ans:
Collapse | Copy Code
// is used for line comments
ex:- var x=10; //comment text
/*
*/
is used for block comments
ex:Collapse | Copy Code
var x= 10; /* this is
block comment example.*/
10) How will you get the Checkbox status whether it is checked or not?
Ans:
Collapse | Copy Code
var status = document.getElementById('checkbox1').checked;
alert(status);
will return true or false.
11) How to create arrays in JavaScript?
Ans:There are two ways to create array in JavaScript like other languages:
a) The first way to create array
Declare Array:
Code
Collapse | Copy Code
var names = new Array();
Add Elements in Array:names[0] = "Vikas";
names[1] = "Ashish";
names[2] = "Nikhil";
b) This is the second way:
Collapse | Copy Code
var names = new Array("Vikas", "Ashish", "Nikhil");
12) If an array with name as "names" contain three elements, then how will you print the third
element of this array?
Ans: Print third array element document.write(names[2]);
Note:- Array index starts with 0.
13) How do you submit a form using JavaScript?
Ans:Use document.forms[0].submit();
14) What does isNaN function do?
Ans: It returns true if the argument is not a number.
Example:
Code
Collapse | Copy Code
document.write(isNaN("Hello")+ "<br>");
document.write(isNaN("2013/06/23")+ "<br>");
document.write(isNaN(123)+ "<br>");
The output will be:
Collapse | Copy Code
true
true
false
15) What is the use of Math Object in JavaScript?
Ans: The math object provides you properties and methods for mathematical constants and
functions.
ex:Code
Collapse | Copy Code
var x = Math.PI; // Returns PI
var y = Math.sqrt(16); // Returns the square root of 16
var z = Math.sin(90);
Returns the sine of 90
16) What do you understand by this keyword in JavaScript?
Ans: In JavaScript the this is a context-pointer and not an object pointer. It gives you the top-most
context that is placed on the stack. The following gives two different results (in the browser, where
by-default the window object is the 0-level context):
Collapse | Copy Code
var obj = { outerWidth : 20 };
function say() {
alert(this.outerWidth);
}
say();//will alert window.outerWidth
say.apply(obj);//will alert obj.outerWidth
17) What does "1"+2+4 evaluate to?
Ans: Since 1 is a string, everything is a string, so the result is 124.
18) What does 3+4+"7" evaluate to?
Ans: Since 3 and 4 are integers, this is number arithmetic, since 7 is a string, it is concatenation,
so 77 is the result.
19) How do you change the style/class on any element using JavaScript?
Ans:
Code
Collapse | Copy Code
document.getElementById(“myText”).style.fontSize = “10";
-orCollapse | Copy Code
document.getElementById(“myText”).className = “anyclass”;
20) Does JavaScript support foreach loop?
Ans: JavaScript 1.6(ECMAScript 5th Edition) support foreach loop,
See example here http://jsfiddle.net/gpDWk/
21) What looping structures are there in JavaScript?
Ans: for, while, do-while loops
22) What is an object in JavaScript, give an example?
Ans: An object is just a container for a collection of named values:
// Create the man object
Code
Collapse | Copy Code
var man = new Object();
man.name = 'Vikas Ahlawat';
man.living = true;
man.age = 27;
23) How you will add function as a property in a JavaScript object? Give an example.
Ans:
Code
Collapse | Copy Code
var man = new Object();
man.name = 'Vikas Ahlawat';
man.living = true;
man.age = 27;
man.getName = function() { return man.name;}
console.log(man.getName()); // Logs 'Vikas Ahlawat'.
24) What is the similarity between the 1st and 2nd statement?
1st:- var myString = new String('male'); // An object.
2nd:- var myStringLiteral = 'male'; // Primitive string value, not an object.
Ans: Both will call String() constructor function
You can confirm it by running the following statement:
Collapse | Copy Code
console.log(myString.constructor, myStringLiteral.constructor);
25) What will be the output of the following statements?
Code
Collapse | Copy Code
var myString = 'Vikas' // Create a primitive string object.
var myStringCopy = myString; // Copy its value into a new variable.
var myString = null; // Manipulate the value
console.log(myString, myStringCopy);
Ans: // Logs 'null Vikas'
26) Consider the following statements and tell what would be the output of the logs
statements?
Collapse | Copy Code
var price1 = 10;
var price2 = 10;
var price3 = new Number('10'); // A complex numeric object because new was used.
console.log(price1 === price2);
console.log(price1 === price3);
Ans:
Collapse | Copy Code
console.log(price1 === price2); // Logs true.
console.log(price1 === price3); /* Logs false because price3
contains a complex number object and price 1
is a primitive value. */
27) What would be the output of the following statements?
Collapse | Copy Code
var object1 = { same: 'same' };
var object2 = { same: 'same' };
console.log(object1 === object2);
What is it?
OpenUI5 is an Open Source JavaScript UI library, maintained by SAP and available
under the Apache 2.0 license. UI5 lets you build enterprise-ready web applications,
responsive to all devices, running on almost any browser of your choice. It’s based on
JavaScript, using JQuery as its foundation and follows web standards. It eases your
development with a client-side HTML5 rendering library including a rich set of controls
and supports data binding to different models (JSON, XML and OData).
View it!
Check out our Explored application for controls running on phones, tablets and desktops,
the interactive control playground for controls running on desktops as well as a number
of sample applications
Get it!
It's FREE. Download the latest UI5 Runtime, the UI5 SDK containing all documentation,
or go to thedownload page for more options.
Get started!
Try the Hello World, read the Developer Guide and refer to the API Reference. Check
outstackoverflow.com to discuss code-related problems and questions. The OpenUI5
team will check regularly here for questions tagged with 'sapui5'. Or join the discussion
in SAP Community Network (SCN).
What's next?
On top of the regular download package updates, source files will be transferred into
a github repository. We’ll offer build and assembly steps for e.g. CSS calculation and
packaging soon. Once these are available contributions can be considered.
Ans: // Logs false, JavaScript does not care that they are identical and of the same object type.
When comparing complex objects, they are equal only when they reference the same object (i.e.,
have the same address). Two variables containing identical objects are not equal to each other since
they do not actually point at the same object.
28) What would be the output of the following statements?
Code
Collapse | Copy Code
var object1 = { same: 'same' };
var object2 = object1;
console.log(object1 === object2);
Ans: // Logs true
29) What is this?
Collapse | Copy Code
var myArray = [[[]]];
Ans: Three dimensional array
30) Name any two JavaScript functions which are used to convert nonnumeric values into
numbers?
Ans:
Collapse | Copy Code
Number()
parseInt()
parseFloat()
Code
Collapse | Copy Code
var
var
var
var
var
n1
n2
n3
n4
n5
=
=
=
=
=
Number(“Hello world!”);
Number(“”);
Number(“000010”);
Number(true);
Number(NaN);
//NaN
//0
//10
//1
//NaN
31) Does JavaScript Support automatic type conversion, If yes give example.
Ans: Yes! Javascript support automatic type conversion. You should take advantage of it, It is most
common way of type conversion used by Javascript developers.
Ex.
Collapse | Copy Code
var s = '5';
var a = s*1;
var b = +s;
typeof(s); //"string"
typeof(a); //"number"
typeof(b); //"number"
The answer to question
7) What is the difference between “==” and “===”?
was
Ans:
“==” checks equality only,
“===” checks for equality as well as the type.
But it should be better
Ans:
“==” checks a weak concept of equality (modulo type coercion) only,
“===” checks for real equality
Javascript interview questions and answers
Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Part 7 Part 8 Part 9
<<Previous Next>>
1.JavaScript vs. Jscript
Latest answer: Both JavaScript and Jscript are almost similar. Java script was developed by Netscape. Microsoft
implemented its own scripting language and named it as Jscript...........
Read answer
2.What is the difference between Client side JavaScript and Server side JavaScript.
Latest answer: Client side java script comprises the basic language and predefined objects which are relevant to
running java script in a browser. The client side java script is embedded directly by in the HTML pages.............
Read answer
3.Where are cookies actually stored on the hard disk?
Latest answer: The storage of cookies on the hard disk depends on OS and the browser. The Netscape navigator
on Windows, the file cookies.txt contains all the cookies. The path is :.........
Read answer
4.What is the difference between a web-garden and a web-farm?
Latest answer: Web garden is a web hosting system. It is a setup of multi processors in single server.
Web farm is a web hosting system. It is a multi-server scenario...........
Read answer
5.What is the difference between SessionState and ViewState?
Latest answer: The values of controls of a particular page of the client browser is persisted by ViewState at the time
of post back operation is done. If the user requests another page, the data of previous page is no longer
available............
Read answer
6.How to Accessing Elements using javascript?
Latest answer: The elements of JavaScript are accessed by their names. By default the browser is accessed by the
element ‘windows’ and the page by ‘document’. The corresponding element has user defined names for forms and its
elements............
Read answer
7.What is the difference between undefined value and null value?
Latest answer: Undefined value: A value that is not defined and has no keyword is known as undefined value. For
example in the declaration, int number; the number has undefined value..........
Read answer
8.How to set the cursor to wait in JavaScript?
Latest answer: The cursor can set to wait in JavaScript by using the property ‘cursor’ property. The following
example illustrates the usage.............
Read answer
9.What is decodeURI(), encodeURI() in JavaScript?
Latest answer: To send the characters that can not be specified in a URL should be converted into their equivalent
hex encoding. To perform this task the methods encodeURI() and decodeURI() are used...........
Read answer
10.Methods GET vs. POST in HTML forms.
Latest answer: Encoding form data into URL is needed by the GET method. The form data is to be appeared within
the message body , by the POST method. By specification, GET is used basically for retrieving data where as POST
is used for data storing, data updating, ordering a product or even e-mailing.............
Read answer
11.What does the EnableViewStateMac setting in an aspx page do?
Latest answer: EnableViewStateMac setting is a security measure in ASP.Net. It ensures the view state for a page
not to tamper. To to so “ EnableViewStateMac=true “is used............
Read answer
12.What are windows object and navigator object in JavaScript?
Latest answer: Windows object is top level object in Java script. It contains several other objects such as, document,
history, location, name, menu bar etc., in itself. Window object is the global object for Java script that is written at
client-side.........
Read answer
13.How to detect the operating system on the client machine in JavaScript?
Latest answer: The navigator.appVersion string should be used to find the name of the operating system on the
client machine..............
Read answer
14.How to set a HTML document's background color in JavaScript?
Latest answer: Using document object the back ground color can be changed by JavaScript.........
Read answer
15.How do you assign object properties in JavaScript?
Latest answer: Java script object properties are assigned like assigning a value to a variable. For example, the title
property of document object can be assigned as follows:
document.title="Welcome to the world of Javascripting";............
Read answer
16.What is JavaScript?
Latest answer: JavaScript is a scripting language most often used for client-side web development...................
Read answer
17.What boolean operators does JavaScript support?
Latest answer: ==, !=, < , >, <=, >=.............
Read answer
18.Is a javascript script faster than an ASP script?
Latest answer: JSP is faster then ASP as the script is run on the client side...................
Read answer
19.What is == operator ?
Latest answer: The ‘==’ operator is a boolean comparison operator that returns true if the variables................
Read answer
20.What is negative infinity?
Latest answer: It’s a number that is obtained by dividing a negative number by zero. (in JSP)...................
Read answer
21.What’s relationship between JavaScript and ECMAScript?
Latest answer: JavaScript is a scripting language most often used for client-side web development...................
Read answer
22.What does isNaN function do?
Latest answer: The isNaN function determines if the value is a number or not and depending upon the result, it
returns true or false.................
Read answer
23.How to read and write a file using javascript?
Latest answer: There are two ways to do it: 1. Using JavaScript extensions (runs from JavaScript Editor), or 2. Using
a web page and ActiveX objects (Internet Explorer only)......................
Read answer
24.How do you create a new object in JavaScript?
Latest answer: In order to generate dynamic content, JSP provides for creating, modifying and interacting with Java
objects. The implicit objects like page, config, request, etc are called so because their availability in the in JSP page
is automatic.....................
Read answer
25.How to create arrays in JavaScript?
Latest answer: Although you can create the arrays using ‘new’ (var myArray = new myArray[10];), it is recommended
that you create it in the following way: var myArray = [];....................
Read answer
Test your Javascript knowledge with our multiple choice questions!
Test your Java skills
Java part 1 (39 questions)
Java part 2 (40 questions)
EJB (20 questions)
JDBC (20 questions)
Applet (20 questions)
Struts (21 questions)
Servlets (20 questions)
Java web services (20 questions)
Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Part 7 Part 8 Part 9
<<Previous Next>>
Also read
OFBiz Service Engine
Defining and creating a Java service
Service parameters
Special unchecked (unmatched) IN/OUT parameters
Security-related programming
Calling services from code (using dispatcher)
IN/OUT parameter mismatch when calling services
Sending feedback; standard return codes success, error and fail
Implementing Service Interfaces
Synchronous and asynchronous services
Using the Service Engine tools
ECAs: Event Condition Actions
The components in the ASP.NET 2.0 AJAX packaging
ASP.NET AJAX Futures Community Technology Preview (CTP) — The ASP.NET 2.0 AJAX framework contains a set
of functionality that is experimental in nature. This functionality will eventually become integrated with the RTM/Core
code.
Potential benefits of using Ajax
AJAX makes it possible to create better and more responsive websites and web applications...............
Potential problems with AJAX
Search engines may not be able to index all portions of your AJAX application site.........
Who Benefits from AJAX?
AJAX is employed to improve the user’s experience. A request is made for the initial page rendering. After that,
asynchronous requests to the server are made. An asynchronous request is a background request to send or receive
data in an entirely nonvisual manner.............
Write your comment - Share Knowledge and Experience
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, whi
are used on keyboards. The constant’s name used is: DOM_VK_KEYNAME, with values representing the keydown/keyup key codes for
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;}
window.onerror=handlerFunction;
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 r
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 diffic
to protect as they can be accessed through many applications and many programs by using the web browsers.
Rohit Sharma 12-11-2011 11:19 AM
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'
+',menubar=0')
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";
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!");
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 al
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;
Rohit Sharma 12-11-2011 11:18 AM
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 browse
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 dia
message like this:
Stop running this script?
A script on this page is causing Internet Explorer to run slowly.
Download