JAVA SCRIPT

Latest JavaScript Interview Questions and Answers
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
<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
<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
<!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:
var name = document.getElementById('txtFullName').value;

alert(name);
or: we can use the old way:
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:
// is used for line comments
ex:- var x=10; //comment text

/*
*/  is used for block comments
ex:-
var x= 10; /* this is
block comment example.*/
10) How will you get the Checkbox status whether it is checked or not?
Ans:
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
var names = new Array();
Add Elements in Array:-
names[0] = "Vikas";
names[1] = "Ashish";
names[2] = "Nikhil";
b) This is the second way: 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
document.write(isNaN("Hello")+ "<br>");
document.write(isNaN("2013/06/23")+ "<br>");
document.write(isNaN(123)+ "<br>");
The output will be: 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
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): 
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
document.getElementById(“myText”).style.fontSize = “10";
-or-
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
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
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:
console.log(myString.constructor, myStringLiteral.constructor);
25) What will be the output of the following statements?
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?
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:
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?
var object1 = { same: 'same' };
var object2 = { same: 'same' };
console.log(object1 === object2);
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
var object1 = { same: 'same' };
var object2 = object1;
console.log(object1 === object2);
Ans: // Logs true
29) What is this?
var myArray = [[[]]];
Ans: Three dimensional array
30) Name any two JavaScript functions which are used to convert nonnumeric values into numbers?
Ans:
Number()
parseInt()
parseFloat()             
Code
var n1 = Number(“Hello world!”); //NaN
var n2 = Number(“”);             //0
var n3 = Number(“000010”);       //10
var n4 = Number(true);           //1
var n5 = Number(NaN);            //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.
var s = '5';
var a = s*1;
var b = +s;
typeof(s); //"string"
typeof(a); //"number"
typeof(b); //"number"

What’s relationship between JavaScript and ECMAScript?
ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3.
How do you submit a form using Javascript?
Use document.forms[0].submit();
(0 refers to the index of the form – if you have more than one form in a page, then the first one has the index 0, second has index 1 and so on).
How do we get JavaScript onto a web page?
You can use several different methods of placing javascript in you pages.
You can directly add a script element inside the body of page.
1. For example, to add the "last updated line" to your pages, In your page text, add the following:
<p>blah, blah, blah, blah, blah.</p>
<script type="text/javascript" >
<!-- Hiding from old browsers
document.write("Last Updated:" +
document.lastModified);
document.close();
// -->
</script>
<p>yada, yada, yada.</p>
(Note: the first comment, "<--" hides the content of the script from browsers that don't understand javascript. The "// -->" finishes the comment. The "//" tells javascript that this is a comment so javascript doesn't try to interpret the "-->". If your audience has much older browsers, you should put this comments inside your javascript. If most of your audience has newer browsers, the comments can be omitted. For brevity, in most examples here the comments are not shown. )
The above code will look like this on Javascript enabled browsers,
2. Javascript can be placed inside the <head> element
Functions and global variables typically reside inside the <head> element.
<head>
<title>Default Test Page</title>
<script language="JavaScript" type="text/javascript">
var myVar = "";
function timer(){setTimeout('restart()',10);}
document.onload=timer();
</script>
</head>

Javascript can be referenced from a separate file
Javascript may also a placed in a separate file on the server and referenced from an HTML page. (Don't use the shorthand ending "<script ... />). These are typically placed in the <head> element.
<script type="text/javascript" SRC="myStuff.js"></script>
How to read and write a file using javascript?
I/O operations like reading or writing a file is not possible with client-side javascript. However , this can be done by coding a Java applet that reads files for the script.
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.
How can JavaScript make a Web site easier to use? That is, are there certain JavaScript techniques that make it easier for people to use a Web site?
JavaScript's greatest potential gift to a Web site is that scripts can make the page more immediately interactive, that is, interactive without having to submit every little thing to the server for a server program to re-render the page and send it back to the client. For example, consider a top-level navigation panel that has, say, six primary image map links into subsections of the Web site. With only a little bit of scripting, each map area can be instructed to pop up a more detailed list of links to the contents within a subsection whenever the user rolls the cursor atop a map area. With the help of that popup list of links, the user with a scriptable browser can bypass one intermediate menu page. The user without a scriptable browser (or who has disabled JavaScript) will have to drill down through a more traditional and time-consuming path to the desired content.
1. Difference between window.onload and onDocumentReady?
The onload event does not fire until every last piece of the page is loaded, this includes css and images, which means there’s a huge delay before any code is executed.
That isnt what we want. We just want to wait until the DOM is loaded and is able to be manipulated. onDocumentReady allows the programmer to do that.
2. What is the difference between == and === ?
The == checks for value equality, but === checks for both type and value.
3. What does “1″+2+4 evaluate to? What about 5 + 4 + “3″?
Since 1 is a string, everything is a string, so the result is 124. In the second case, its 93.
4. What is the difference between undefined value and null value?
undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value.
Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.
Unassigned variables are initialized by JavaScript with a default value of undefined. JavaScript never sets a value to null. That must be done programmatically.
5. How do you change the style/class on any element?
document.getElementById(“myText”).style.fontSize = “20″;
-or-
document.getElementById(“myText”).className = “anyclass”;
6. What are Javascript closures?When would you use them?
Two one sentence summaries:
* a closure is the local variables for a function – kept alive after the function has returned, or
* a closure is a stack-frame which is not deallocated when the function returns.
A closure takes place when a function creates an environment that binds local variables to it in such a way that they are kept alive after the function has returned. A closure is a special kind of object that combines two things: a function, and any local variables that were in-scope at the time that the closure was created.
The following code returns a reference to a function:
function sayHello2(name) {
var text = ‘Hello ‘ + name; // local variable
var sayAlert = function() { alert(text); }
return sayAlert;
}
Closures reduce the need to pass state around the application. The inner function has access to the variables in the outer function so there is no need to store the information somewhere that the inner function can get it.
This is important when the inner function will be called after the outer function has exited. The most common example of this is when the inner function is being used to handle an event. In this case you get no control over the arguments that are passed to the function so using a closure to keep track of state can be very convenient.
7. What is unobtrusive javascript? How to add behavior to an element using javascript?
Unobtrusive Javascript refers to the argument that the purpose of markup is to describe a document’s structure, not its programmatic behavior and that combining the two negatively impacts a site’s maintainability. Inline event handlers are harder to use and maintain, when one needs to set several events on a single element or when one is using event delegation.
1
<input type="text" name="date" />

Say an input field with the name “date” had to be validated at runtime:
1
2
3
4
5
6
document.getElementsByName("date")[0].
                   addEventListener("change", validateDate, false);
  
function validateDate(){
// Do something when the content of the 'input' element with the name 'date' is changed.
}

Although there are some browser inconsistencies with the above code, so programmers usually go with a javascript library such as JQuery or YUI to attach behavior to an element like above.
8.  What is Javascript namespacing? How and where is it used?
Using global variables in Javascript is evil and a bad practice. That being said, namespacing is used to bundle up all your functionality using a unique name. In JavaScript, a namespace is really just an object that you’ve attached all further methods, properties and objects. It promotes modularity and code reuse in the application.
9.  What datatypes are supported in Javascript?
Number, String, Undefined, null, Boolean
10. What is the difference between innerHTML and append() in JavaScript?
InnerHTML is not standard, and its a String. The DOM is not, and although innerHTML is faster and less verbose, its better to use the DOM methods like appendChild(), firstChild.nodeValue, etc to alter innerHTML content.

What is the difference between undefined and null?

The value of a variable with no value is undefined (i.e., it has not been initialized). Variables can be emptied by setting their value to null. You can test for each using the === (three equal signs) or == (two equal signs) for comparison checking. The big difference is the latter uses coercion, which can have some odd results -- it returns true for a null or undefined comparison if they are either.
if (nullExample === null) { // executes this block only if null }
if (undExample ===Undefined) { // executes this block only if Undefined }
 
if (bothExampe == null) { // executes this block if Undefined or null }
You can be more exact with a comparison by using the typeof to return an object's type.
If (typeof variable ==="undefined")  { // executes this block of if undefined }

What is JavaScript's this keyword?

JavaScript's this keyword normally refers to the object that owns the method, but it depends on how a function is called. Basically, it points to the currently in scope object that owns where you are in the code. When working within a Web page, this usually refers to the Window object. If you are in an object created with the new keyword, the this keyword refers to the object being created. When working with event handlers, JavaScript's this keyword will point to the object that generated the event.

What is event bubbling?

Event bubbling describes the behavior of events in child and parent nodes in the Document Object Model (DOM); that is, all child node events are automatically passed to its parent nodes. The benefit of this method is speed, because the code only needs to traverse the DOM tree once. This is useful when you want to place more than one event listener on a DOM element since you can put just one listener on all of the elements, thus code simplicity and reduction. One application of this is the creation of one event listener on a page's body element to respond to any click event that occurs within the page's body.

Do you have a JavaScript framework preference? What are your thoughts on using frameworks?

This open-ended question has the potential to spawn a good conversation. There are the vastly popular frameworks like jQuery, although you might be surprised when the person tells you about the framework they developed or even played the contributor role.
The answer to the second question gives you an idea of the candidate's feelings about open source (well, that is the way I see it). There are so many open source options available today (Knockout, postal.js, jQuery, etc.), and a developer's time is very valuable, so why reinvent the wheel? These open source options provide robust code that has been thoroughly tested by an army of developers. From my perspective, I want developers who will use whatever is available to meet a project's demands. Plus, the interviewee might introduce you to something you've never used.

How are errors gracefully handled in JavaScript?

Exceptions that occur at runtime can be handled via try/catch/finally blocks; this allows you to avoid those unfriendly error messages. The finally block is optional, as the bare minimum to use is try/catch. Basically, you try to run code (in the try block between the braces), and execution is transferred to the catch block of code when/if runtime errors occur. When the try/catch block is finally done, code execution transfers to the finally code block. This is the same way it works in other languages like C# and Java.
try {
// do something
 
} catch (e) {
// do something with the exception
} finally {
// This code block always executes whether there is an exception or not.
}
You can give bonus points to any candidate who discusses the onerror event handler tied to the Window object in the browser -- this allows it to monitor all errors on a page. This allows you to properly handle code syntax errors and runtime exceptions.

How do JavaScript timers work? What is a drawback of JavaScript timers?

Timers allow you to execute code at a set time or repeatedly using an interval. This is accomplished with the setTimeout, setInterval, and clearInterval functions. The setTimeout(function, delay) function initiates a timer that calls a specific function after the delay; it returns an id value that can be used to access it later. The setInterval(function, delay) function is similar to the setTimeout function except that it executes repeatedly on the delay and only stops when cancelled. The clearInterval(id) function is used to stop a timer. Timers can be tricky to use since they operate within a single thread, thus events queue up waiting to execute.

Difference Between Java Script & Jquery?

What is JavaScript?
•JavaScript was designed to add interactivity to HTML pages
•JavaScript is a scripting language
•A scripting language is a lightweight programming language
•JavaScript is usually embedded directly into HTML pages
•JavaScript is an interpreted language (means that scripts execute without preliminary compilation)
•Everyone can use JavaScript without purchasing a license
.Animation is not possible in javascript

What is JQuery?
JQuery is a JavaScript library that handles many commonly used features and also handles the differences between, e.g., Internet Explorer and standards-compliant browsers. It's something you can use to reduce the amount of work when creating web-based applications.
note : Everyone can use JQuery without purchasing a license
note : JQuery made by Java Script
.animation is possible in jquery


Ascii Value of Chaacters & Special symbols in Java Script

Example :     OnClientClick='<%# String.Format("fnCheckActive(&#39;{0}&#39;)", Eval("IS_ACTIVE"))%>'>

ASCII / HTML Codes
ASCII    HTML    CHR 0034    & #34;     "
0035    & #35;     #
0036    & #36;     $
0037    & #37;     %
0038    & #38;     &
0039    & #39;     '
0040    & #40;     (
0041    & #41;     )
0042    & #42;     *
0043    & #43;     +
0044    & #44;     ,
0045    & #45;     -
0046    & #46;     .
0047    & #47;     /
0048    & #48;     0
0049    & #49;     1
0050    & #50;     2
0051    & #51;     3
0052    & #52;     4
0053    & #53;     5
0054    & #54;     6
0055    & #55;     7
0056    & #56;     8
0057    & #57;     9
0058    & #58;     :
0059    & #59;     ;
0060    & #60;     <
0061    & #61;     =
0062    & #62;     >
0063    & #63;     ?
0064    & #64;     @
0065    & #65;     A
0066    & #66;     B
0067    & #67;     C
0068    & #68;     D
0069    & #69;     E
0070    & #70;     F
0071    & #71;     G
0072    & #72;     H
0073    & #73;     I
0074    & #74;     J
0075    & #75;     K
0076    & #76;     L
0077    & #77;     M
0078    & #78;     N
0079    & #79;     O
0080    & #80;     P
ASCII    HTML    CHR 0081    & #81;     Q
0082    & #82;     R
0083    & #83;     S
0084    & #84;     T
0085    & #85;     U
0086    & #86;     V
0087    & #87;     W
0088    & #88;     X
0089    & #89;     Y
0090    & #90;     Z
0091    & #91;     [
0092    & #92;     \
0093    & #93;     ]
0094    & #94;     ^
0095    & #95;     _
0096    & #96;     `
0097    & #97;     a
0098    & #98;     b
0099    & #99;     c
0100    & #100;   d
0101    & #101;   e
0102    & #102;   f
0103    & #103;   g
0104    & #104;   h
0105    & #105;   i
0106    & #106;   j
0107    & #107;   k
0108    & #108;   l
0109    & #109;   m
0110    & #110;   n
0111    & #111;   o
0112    & #112;   p
0113    & #113;   q
0114    & #114;   r
0115    & #115;   s
0116    & #116;   t
0117    & #117;   u
0118    & #118;   v
0119    & #119;   w
0120    & #120;   x
0121    & #121;   y
0122    & #122;   z
0123    & #123;   {
0124    & #124;   |
0125    & #125;   }
0126    & #126;   ~
0127    & #127;   n/a
ASCII    HTML    CHR 0128    & #128;     €
0129    & #129;     
0130    & #130;     ‚
0131    & #131;     ƒ
0132    & #132;     „
0133    & #133;     ...
0134    & #134;     †
0135    & #135;     ‡
0136    & #136;     ˆ
0137    & #137;     ‰
0138    & #138;     Š
0139    & #139;     ‹
0140    & #140;     Œ
0141    & #141;     
0142    & #142;     Ž
0143    & #143;     
0144    & #144;     
0145    & #145;     ‘
0146    & #146;     ’
0147    & #147;     “
0148    & #148;     ”
0149    & #149;     •
0150    & #150;     –
0151    & #151;     —
0152    & #152;     ˜
0153    & #153;     ™
0154    & #154;     š
0155    & #155;     ›
0156    & #156;     œ
0157    & #157;     
0158    & #158;     ž
0159    & #159;     Ÿ
0160    & #160;     n/a
0161    & #161;     ¡
0162    & #162;     ¢
0163    & #163;     £
0164    & #164;     ¤
0165    & #165;     ¥
0166    & #166;     ¦
0167    & #167;     §
0168    & #168;     ¨
0169    & #169;     ©
0170    & #170;     ª
0171    & #171;     «
0172    & #172;     ¬
0173    & #173;     ­
0174    & #174;     ®
ASCII    HTML    CHR 0175    & #175;     ¯
0176    & #176;     °
0177    & #177;     ±
0178    & #178;     ²
0179    & #179;     ³
0180    & #180;     ´
0181    & #181;     µ
0182    & #182;     ¶
0183    & #183;     ·
0184    & #184;     ¸
0185    & #185;     ¹
0186    & #186;     º
0187    & #187;     »
0188    & #188;     ¼
0189    & #189;     ½
0190    & #190;     ¾
0191    & #191;     ¿
0192    & #192;     À
0193    & #193;     Á
0194    & #194;     Â
0195    & #195;     Ã
0196    & #196;     Ä
0197    & #197;     Å
0198    & #198;     Æ
0199    & #199;     Ç
0200    & #200;     È
0201    & #201;     É
0202    & #202;     Ê
0203    & #203;     Ë
0204    & #204;     Ì
0205    & #205;     Í
0206    & #206;     Î
0207    & #207;     Ï
0208    & #208;     Ð
0209    & #209;     Ñ
0210    & #210;     Ò
0211    & #211;     Ó
0212    & #212;     Ô
0213    & #213;     Õ
0214    & #214;     Ö
0215    & #215;     ×
0216    & #216;     Ø
0217    & #217;     Ù
0218    & #218;     Ú
0219    & #219;     Û
0220    & #220;     Ü
0221    & #221;     Ý
ASCII    HTML    CHR 0222    & #222;     Þ
0223    & #223;     ß
0224    & #224;     a
0225    & #225;     á
0226    & #226;     â
0227    & #227;     ã
0228    & #228;     ä
0229    & #229;     å
0230    & #230;     æ
0231    & #231;     ç
0232    & #232;     è
0233    & #233;     é
0234    & #234;     ê
0235    & #235;     ë
0236    & #236;     ì
0237    & #237;     í
0238    & #238;     î
0239    & #239;     ï
0240    & #240;     ð
0241    & #241;     ñ
0242    & #242;     ò
0243    & #243;     ó
0244    & #244;     ô
0245    & #245;     õ
0246    & #246;     ö
0247    & #247;     ÷
0248    & #248;     ø
0249    & #249;     ù
0250    & #250;     ú
0251    & #251;     û
0252    & #252;     ü
0253    & #253;     ý
0254    & #254;     þ
0255    & #255;     ÿ


No comments:

Post a Comment