Pages

Friday, August 26, 2016

JAVASCRIPT Questions and Answers 2016

1. Which of the following Array methods in JavaScript runs a function on every item in the Array and collects the result from previous calls, but in reverse?
Answers:
  1. reduce()
  2. reduceRight()
  3. everse()
  4. pop()
2. Which of the following is true about setTimeOut()?
Answers:
  1. The statement(s) it executes run(s) only once.
  2. It pauses the script in which it is called.
  3. clearTimeOut() won’t stop its execution.
  4. The delay is measured in hundredths of a second.
  5. It is required in every JavaScript function.
3. How can the operating system of the client machine be detected?
Answers:
  1. It is not possible using JavaScript.
  2. Using the navigator object
  3. Using the window object
  4. Using the document object
  5. None of these.
4. Which of the following prints “AbBc”?
Answers:
  1. var b = ‘a’; var result = b.toUpperCase() + ‘b’ + ‘b’.toUpperCase() +’C'[‘toLowerCase’](); alert(result);
  2. var b = ‘a’; var result = b.toUpperCase() + ‘b’ + ‘b’.toUpperCase() +’c'[‘toUpperCase’](); alert(result);
  3. var b = ‘a’; var result = b.toUpperCase() + b + ‘b’.toUpperCase() +’C'[‘toLowerCase’](); alert(result);
  4. var b = ‘a’; var result = b.toUpperCase() + ‘b’ + ‘b’.toUpperCase() +C; alert(result);
5. Which of the following descriptions is true for the code below?
var object0 = {};
Object.defineProperty(object0, “prop0”, { value : 1, enumerable:false, configurable : true });
Object.defineProperty(object0, “prop1”, { value : 2, enumerable:true, configurable : false });
Object.defineProperty(object0, “prop2”, { value : 3 });
object0.prop3 = 4;
Answers:
  1. Object ‘object0’ contains 4 properties. Property ‘prop2’ and property ‘prop3’ are available in the for…in loop. Property ‘prop0’ and property ‘prop1’ are available to delete.
  2. Object ‘object0’ contains 4 properties. Property ‘prop1’ and property ‘prop2’ are available in the for…in loop. Property ‘prop2’ and property ‘prop3’ are available to delete.
  3. Object ‘object0’ contains 4 properties. Property ‘prop0’ and property ‘prop2’ are available in the for…in loop. Property ‘prop0’ and property ‘prop2’ are available to delete.
  4. Object ‘object0’ contains 4 properties. Property ‘prop1’ and property ‘prop3’ are available in the for…in loop. Property ‘prop0’ and property ‘prop3’ are available to delete.
6. Performance-wise, which is the fastest way of repeating a string in JavaScript?
Answers:
  1. String.prototype.repeat = function( num ) { return new Array( num + 1 ).join( this ); }
  2. function repeat(pattern, count) { if (count < 1) return ”; var result = ”; while (count > 0) { if (count & 1) result += pattern; count >>= 1, pattern += pattern; } return result; }
  3. String.prototype.repeat = function(count) { if (count < 1) return ”; var result = ”, pattern = this.valueOf(); while (count > 0) { if (count & 1) result += pattern; count >>= 1, pattern += pattern; } return result; };
  4. String.prototype.repeat = function (n, d) { return –n ? this + (d || ”) + this.repeat(n, d) : ” + this };
7. Consider the following variable declarations:
var a=”adam”
var b=”eve”
Which of the following would return the sentence “adam and eve”?
Answers:
  1. a.concatinate(“and”, b)
  2. a.concat(“and”, b)
  3. a.concatinate(” and “, b)
  4. a.concat(” and “, b)
8. Which of the following code snippets will correctly split “str”?
Answers:
  1. <script> var str = ‘something — something_else’; var substrn = str.split(‘ — ‘); </script>
  2. <script> var str = ‘something — something_else’; var substrn = split.str(‘ — ‘); </script>
  3. <script> var str = ‘something — something_else’; var substrn = str.split(‘ – ‘,’ – ‘); </script>
  4. <script> var str = ‘something — something_else’; var substrn = split.str(‘ – ‘,’ – ‘); </script>
9. Which object can be used to ascertain the protocol of the current URL?
Answers:
  1. document
  2. window
  3. history
  4. browser
  5. form
  6. location
10. Which of the following best describes a “for” loop?
Answers:
  1. “for” loop consists of six optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
  2. “for” loop consists of five optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
  3. “for” loop consists of four optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
  4. “for” loop consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
11. Which of the following descriptions best describes the code below?
<script>
var variable1 = { fastFood: “spaghetti”, length: 10 };
Object.freeze(variable1);
variable1.price = 50;
delete variable1.length;
</script>
Answers:
  1. Object is frozen, a property named “price” is added in the variable1 object, a property named “length” is deleted from this object. At the end of the code, the object “variable1” contains 2 properties.
  2. Object is frozen, a property named “price” is not added in the variable1 object, a property named “length” is deleted from this object. At the end of the code, object “variable1” contains 1 properties.
  3. Object is frozen, a property named “price” is added in the variable1 object, a property named “length” is not deleted from this object. At the end of the code, object “variable1” contains 1 properties.
  4. Object is frozen, a property named “price” is not added in the variable1 object, a property named “length” is not deleted from this object. At the end of the code, object “variable1” contains 2 properties.
12. Which of the following is not a valid HTML event?
Answers:
  1. ondblclick
  2. onmousemove
  3. onclick
  4. onblink
13. Analyze the following code snippet which uses a Javascript Regular Expression character set. What will be the output of this code?
<html>
<body>
<script type=”text/javascript”>
var str = “Is this enough?”;
var patt1 = new RegExp(“[^A-J]”);
var result = str.match(patt1);
document.write(result);
</script>
</body>
</html
Answers:
  1. I
  2. Is
  3. s
  4. I,s,
14. Consider the following image definition:
<img id=”logo” src=”companylogo1.gif” height=”12″ width=”12″ >
Which of the following will change the image to companylogo2.gif when the page loads?
Answers:
  1. logo.source=”companylogo2.gif”
  2. logo.source=”companylogo1.gif”
  3. document.getElementById(‘logo’).src=”companylogo1.gif”
  4. document.getElementById(‘logo’).src=”companylogo2.gif”
15. What is the final value of the variable bar in the following code?
var foo = 9;
bar = 5;
(function() {
var foo = 2;
bar= 1;
}())
bar = bar + foo;
Answers:
  1. 10
  2. 14
  3. 3
  4. 7
16. Which of the following are JavaScript unit testing tools?
Answers:
  1. Buster.js, jQuery, YUI Yeti
  2. QUnit, Modernizr, JsTestDriver
  3. Node.js, Modernizr, Jasmine
  4. Buster.js, YUI Yeti, Jasmine
17. Which of the following can be used for disabling the right click event in Internet Explorer?
Answers:
  1. event.button == 2
  2. event.button == 4
  3. event.click == 2
  4. event.click == 4
18. An image tag is defined as follows:
<img id=”ERImage” width=”100″ height=”100″ onmouseover=”ImageChange()” src=”Image1.jpg”>
The purpose of the ImageChange() function is to change the image source to Image2.jpg. Which of the following should the ImageChange() function look like?
Answers:
  1. document.getElementById(‘ERImage’).src=”Image1.jpg”
  2. document.getElementById(‘ERImage’).src=”Image2.jpg”
  3. document.getElementById(‘ERImage’).style.src=”Image1.jpg”
  4. document.getElementById(‘ERImage’).style.src=”Image2.jpg”
19. Consider the following JavaScript alert:
<script type=”text/JavaScript”>
function message() {
alert(“Welcome to ExpertRating!!!”)
}
</script>
Which of the following will run the function when a user opens the page?
Answers:
  1. body onload=”message()”
  2. body onunload=”message()”
  3. body onsubmit=”message()”
  4. body onreset=”message()”
20. Which of the following code snippets will correctly get the length of an object?
Answers:
  1. <script> var newObj = new Object(); newObj[“firstname”] = “FirstName”; newObj[“lastname”] = “LastName”; newObj[“age”] = 21; Object.size = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(index)) size++; } return size; }; var size = Object.size(newObj); </script>
  2. <script> var newObj = new Object(); newObj[“firstname”] = “FirstName”; newObj[“lastname”] = “LastName”; newObj[“age”] = 21; Object.size = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(value)) size++; } return size; }; var size = Object.size(newObj); </script>
  3. <script> var newObj = new Object(); newObj[“firstname”] = “FirstName”; newObj[“lastname”] = “LastName”; newObj[“age”] = 21; Object.size = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(length)) size++; } return size; }; var size = Object.size(newObj); </script>
  4. <script> var newObj = new Object(); newObj[“firstname”] = “FirstName”; newObj[“lastname”] = “LastName”; newObj[“age”] = 21; Object.size = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; var size = Object.size(newObj); </script>
21. In an HTML page, the form tag is defined as follows:
<form onsubmit=”return Validate()” action=”http://www.mysite.com/”>
The validate() function is intended to prevent the form from being submitted if the name field in the form is empty. What should the validate() function look like?
Answers:
  1. <script type=”text/javascript”> function Validate() { if(document.forms[0].name.value == “”) return true; else return false; } </script>
  2. <script type=”text/javascript”> function Validate() { if(document.forms[0].name.value == “”) return false; else return true; } </script>
  3. script type=”text/javascript”> function Validate() { if(document.forms[0].name== “”) return false; else return true; } </script>
  4. <script type=”text/javascript”> function Validate() { if(document.forms[0].name == “”) return true; else return false; } </script>
22. Which of the following code snippets changes an image on the page?
Answers:
  1. var img = document.getElementById(“imageId”); img.src = “newImage.gif”;
  2. var img = document.getElementById(“imageId”); img.style.src = “newImage.gif”;
  3. var img = document.getElementById(“imageId”); img.src.value = “newImage.gif”;
  4. var img = document.getElementById(“imageId”); img = “newImage.gif”;
23. Which of the following results is returned by the JavaScript operator “typeof” for the keyword “null”?
Answers:
  1. function
  2. object
  3. string
  4. number
24. What will be the final value of the variable “apt”?
var apt=2;
apt=apt<<2;
Answers:
  1. 2
  2. 4
  3. 6
  4. 8
  5. 16
25. How can a JavaScript object be printed?
Answers:
  1. console.log(obj)
  2. console.print(obj)
  3. console.echo(obj);
  4. None of these
26. Which of the following is the correct syntax for using the JavaScript exec() object method?
Answers:
  1. RegExpObject.exec()
  2. RegExpObject.exec(string)
  3. RegExpObject.exec(parameter1,parameter2)
  4. None of these
27. Having an array object var arr = new Array(), what is the best way to add a new item to the end of an array?
Answers:
  1. arr.push(“New Item”)
  2. arr[arr.length] = “New Item”
  3. arr.unshift(“New Item”)
  4. arr.append(“New Item”)
28. Consider the following JavaScript validation function:
function ValidateField()
{
if(document.forms[0].txtId.value ==””)
{return false;}
return true;
}
Which of the following options will call the function as soon as the user leaves the field?
Answers:
  1. input name=txtId type=”text” onreset=”return ValidateField()”
  2. input name=txtId type=”text” onfocus=”return ValidateField()”
  3. input name=txtId type=”text” onsubmit=”return ValidateField()”
  4. input name=txtId type=”text” onblur=”return ValidateField()”
29. Which of following uses the “with” statement in JavaScript correctly?
Answers:
  1. with (document.getElementById(“blah”).style) { background = “black”; color = “blue”; border = “1px solid green”; }
  2. with document.getElementById(“blah”).style background = “black”; color = “blue”; border = “1px solid green”; End With
  3. With document.getElementByName(“blah”).style background = “black”; color = “blue”; border = “1px solid green”; End With
  4. with (document.getElementById(“blah”).style) { .background = “black”; .color = “blue”; .border = “1px solid green”; }
30. Consider the following JavaScript validation function:
<script type=”text/JavaScript”>
function ValidateField()
{
if(document.forms[0].txtId.value ==””)
{return false;}
return true;
}
</script>
Which of the following options will call the function as soon as the user leaves the field?
Answers:
  1. input name=txtId type=”text” onreset=”return ValidateField()”
  2. input name=txtId type=”text” onfocus=”return ValidateField()”
  3. input name=txtId type=”text” onsubmit=”return ValidateField()”
  4. input name=txtId type=”text” onblur=”return ValidateField()”
31. Which of the following modifiers must be set if the JavaScript lastIndex object property was used during pattern matching?
Answers:
  1. i
  2. m
  3. g
  4. s
32. Consider the following image definition:
<img id=”logo” src=”companylogo1.gif” height=”12″ width=”12″ >
Which of the following will change the image to “companylogo2.gif” when the page loads?
Answers:
  1. logo.source=”companylogo2.gif”
  2. logo.source=”companylogo1.gif”
  3. document.getElementById(‘logo’).src=”companylogo1.gif”
  4. document.getElementById(‘logo’).src=”companylogo2.gif”
33. Which of the following will check whether the variable vRast exists or not?
Answers:
  1. if (typeof vRast=”undefined”) {}
  2. if (typeof vRast ==”undefined”) {}
  3. if (vRast.defined =true) {}
  4. if (vRast.defined ==true) {}
34. What would be the use of the following code?
function validate(field) {
var valid=”ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz”;
var ok=”yes”;
var temp;
for(var i=0;i<field.value.length;i++) {
temp=”” + field.value.substring(i,i+1)
if(valid.indexOf(temp)==”-1”) {
ok=”no”;
}
}
if(ok==”no”) {
alert(”error”);
field.focus();
}
}
Answers:
  1. It will force a user to enter only numeric values.
  2. It will force a user to enter only alphanumeric values.
  3. It will force a user to enter only English alphabet character values.
  4. None of these.
35. An image tag is defined as follows:
<img id=”ERImage” width=”100″ height=”100″ onmouseover=”ImageChange()” src=”Image1.jpg”>
The purpose of the ImageChange() function is to change the image source to “Image2.jpg”. Which of the following should the ImageChange() function look like?
Answers:
  1. document.getElementById(‘ERImage’).src=”Image1.jpg”
  2. document.getElementById(‘ERImage’).src=”Image2.jpg”
  3. document.getElementById(‘ERImage’).style.src=”Image1.jpg”
  4. document.getElementById(‘ERImage’).style.src=”Image2.jpg”
36. Which of the following choices will detect if “variableName” declares a function?
<script>
var variableName= function(){};
</script>
Answers:
  1. return variableName;
  2. nameof variableName;
  3. isFunction variableName;
  4. typeof variableName;
37. Which of the following choices will change the source of the image to “image2.gif” when a user clicks on the image?
Answers:
  1. img id=”imageID” src=”image1.gif” width=”50″ height=”60″ onmousedown=”changeimg(image1.gif)” onmouseup=”changeimg(image2.gif)”
  2. img id=”imageID” src=”image1.gif” width=”50″ height=”60″ onmouseclick=”changeimg(image2.gif)” onmouseup=”changeimg(image1.gif)”
  3. img id=”imageID” src=”image2.gif” width=”50″ height=”60″ onmousedown=”changeimg(image1.gif)” onmouseup=”changeimg(image2.gif)”
  4. img id=”imageID” src=”image2.gif” width=”50″ height=”60″ onmousedown=”changeimg(image2.gif)” onmouseup=”changeimg(image1.gif)”
  5. img id=”imageID” src=”image1.gif” width=”50″ height=”60″ onmousedown=”changeimg(‘image2.gif’)” onmouseup=”changeimg(‘image1.gif’)”
38. How can created cookies be deleted using JavaScript?
Answers:
  1. They can’t be deleted. They are valid until they expire.
  2. Overwrite with an expiry date in the past
  3. Use escape() on the value of the path attribute
  4. Use unescape() on the value of the path attribute
  5. The cookie file will have to be removed from the client machine.
  6. Wait till the expiry date is reached
39. What would be the value of ‘ind’ after execution of the following code?
var msg=”Welcome to ExpertRating”
var ind= msg.substr(3, 3)
Answers:
  1. lco
  2. com
  3. ome
  4. Welcome
40. Are the two statements below interchangeable?
object.property
object[”property”]
Answers:
  1. Yes
  2. No
41. Which of the following is not a valid method in generator-iterator objects in JavaScript?
Answers:
  1. send()
  2. throw()
  3. next()
  4. stop()
42. Which of the following code snippets will return all HTTP headers?
Answers:
  1. var req = new XMLHttpRequest(); req.open(‘GET’, document.location, false); req.send(null); var headers = req.getAllResponseHeaders().toLowerCase(); alert(headers);
  2. var req = new XMLHttpAccess(); req.open(‘GET’, document.location, false); req.send(null); var headers = req.getAllResponseHeaders().toLowerCase(); alert(headers);
  3. var req = new XMLHttpRequest(); req.open(‘GET’, document.location, false); req.send(null); var headers = req.getResponseHeader().toLowerCase(); alert(headers);
  4. var req = new XMLHttpRequestHeader(); req.open(‘GET’, document.location, false); req.send(null); var headers = req.retrieveAllResponseHeaders().toLowerCase(); alert(headers);
43. Consider the following JavaScript alert:
<script type=”text/JavaScript”>
function message() {
alert(“Welcome to ExpertRating!!!”)
}
</script>
Which of the following will run the function when a user opens the page?
Answers:
  1. body onload=”message()”
  2. body onunload=”message()”
  3. body onsubmit=”message()”
  4. body onreset=”message()”
44. Which of the following is the most secure and efficient way of declaring an array?
Answers:
  1. var a = []
  2. var a = new Array()
  3. var a = new Array(n)
  4. var a
45. Which of the following Regular Expression pattern flags is not valid?
Answers:
  1. gi
  2. p
  3. i
  4. g
46. Which of the following built-in functions is used to access form elements using their IDs?
Answers:
  1. getItem(id)
  2. getFormElement(id)
  3. getElementById(id)
  4. All of these
47. Which of the following statements is correct?
Answers:
  1. There is no undefined property in JavaScript.
  2. Undefined object properties can be checked using the following code: if (typeof something == null) alert(“something is undefined”);
  3. It is not possible to check for undefined object properties in JavaScript.
  4. Undefined object properties can be checked using the following code: if (typeof something === “undefined”) alert(“something is undefined”);
48. Which of the following correctly uses a timer with a function named rearrange()?
Answers:
  1. tmr=setTimeout(“rearrange ()”,1)
  2. tmr=Timer(1,”rearrange ()”)
  3. tmr=Timer(“rearrange ()”,1)
  4. tmr=setTimeout(1,”rearrange ()”)
49. Which of the following can be used to escape the ‘ character?
Answers:
  1. *
  2. \
  3. @
  4. #
  5. %
  6. |
  7. ~
50. Which event can be used to validate the value in a field as soon as the user moves out of the field by pressing the tab key?
Answers:
  1. onblur
  2. onfocus
  3. lostfocus
  4. gotfocus
  5. None of these
51. When setting cookies with JavaScript, what will happen to the cookies.txt data if the file exceeds the maximum size?
Answers:
  1. The script automatically generates a run-time error.
  2. The script automatically generates a load-time error.
  3. All processes using document.cookie are ignored.
  4. The file is truncated to the maximum length.
52. Which of the following are not global methods and properties in E4X?
Answers:
  1. ignoreComments
  2. ignoreWhiteSpace
  3. setName()
  4. setNamespace()
  5. ignoreComments and ignoreWhiteSpace
  6. setName() and setNamespace()
53. Which of the following will change the color of a paragraph’s text to blue when a user hovers over it, and reset it back to black when the user hovers out?
Answers:
  1. <p onmouseover=”style.color=’black'” onmouseout=”style.color=’blue'”> The text of the paragraph..</p>
  2. <p onmouseover=”style.color=’blue'” onmouseout=”style.color=’black'”> The text of the paragraph..</p>
  3. <p onmouseout=”style.color=’blue'”> The text of the paragraph..</p>
  4. <p onmouseover=”style.color=’blue'”> The text of the paragraph..</p>
  5. <p onmousein=”style.color=’blue'” onmouseout=”style.color=’black'”> The text of the paragraph..</p>
54. What is the purpose of while(1) in the following JSON response?
while(1);[[‘u’,[[‘smsSentFlag’,’false’],[‘hideInvitations’,’false’],[‘remindOnRespondedEventsOnly’,’true’],[‘hideInvitations_remindOnRespondedEventsOnly’,’false_true’],[‘Calendar ID stripped for privacy’,’false’],[‘smsVerifiedFlag’,’true’]]]]
Answers:
  1. It’s invalid JSON code.
  2. It makes it difficult for a third-party to insert the JSON response into an HTML document with a <script> tag.
  3. It iterates the JSON response.
  4. It prevents the JSON response from getting executed.
55. Consider the three variables:
someText = ‘JavaScript1.2’;
pattern = /(w+)(d).(d)/i;
outCome = pattern.exec(someText);
What does outCome[0] contain?
Answers:
  1. true
  2. false
  3. JavaScript1.2
  4. null
  5. 0
56. Which of the following choices will turn a string into a JavaScript function call (case with objects) of the following code snippet?
<script>
window.foo = {
bar: {
baz: function() {
alert(‘Hello!’);
}
}
};
</script>
Answers:
  1. bar[‘baz’]();
  2. object[‘foo’][‘bar’][‘baz’]();
  3. document[‘foo’][‘bar’][‘baz’]();
  4. window[‘foo’][‘bar’][‘baz’]();
57. Which of the following determines whether cookies are enabled in a browser or not?
Answers:
  1. (navigator.Cookie)? true : false
  2. (application.cookieEnabled)? true : false
  3. (navigator.cookieEnabled)? true : false
  4. (application.cookie)? true : false
58. Which of the following options can be used for adding direct support for XML to JavaScript?
Answers:
  1. E4X
  2. egex
  3. Generators and Iterators
  4. let
59. Which of the following will detect which DOM element has the focus?
Answers:
  1. document.activeElement
  2. document.ready
  3. document.referrer
  4. document.getelementbyid
60. Which of the following will randomly choose an element from an array named myStuff, given that the number of elements changes dynamically?
Answers:
  1. randomElement = myStuff[Math.floor(Math.random() * myStuff.length)];
  2. randomElement = myStuff[Math.ceil(Math.random() * myStuff.length)];
  3. randomElement = myStuff[Math.random(myStuff.length)];
  4. randomElement = Math.random(myStuff.length);
61. How can global variables be declared in JavaScript?
Answers:
  1. All variables are local in JavaScript.
  2. Declare the variable between the ‘script’ tags, and outside a function to make the variable global
  3. Precede the variable name with the constant global
  4. Declare the variable in an external file
62. Which of the following objects in JavaScript contains the collection called “plugins”?
Answers:
  1. Location
  2. Window
  3. Screen
  4. Navigator
63. What will be output of the following code?
function testGenerator() {
yield “first”;
document.write(“step1”);
yield “second”;
document.write(“step2”);
yield “third”;
document.write(“step3”);
}
var g = testGenerator();
document.write(g.next());
document.write(g.next());
Answers:
  1. firststep1second
  2. step1step2
  3. step1
  4. step1step2step3
64. Which of the following methods will copy data to the Clipboard?
Answers:
  1. execClipboard(‘Copy’)
  2. copyCommand(‘Clipboard’)
  3. execCommand(‘Copy’)
  4. execClipboard(‘Copy’)
65. Which of the following code snippets trims whitespace from the beginning and end of the given string str?
Answers:
  1. str.replace(/^s+|s+$/g, ”);
  2. str.replace(/^s+/,”);
  3. str.replace(/s+$/,”);
  4. str.replace(/s+/g,’ ‘);
66. What is the difference between call() and apply()?
Answers:
  1. The call() function accepts an argument list of a function, while the apply() function accepts a single array of arguments.
  2. The apply() function accepts an argument list of a function, while the call() function accepts a single array of arguments.
  3. The call() function accepts an object list of a function, while the apply() function accepts a single array of an object.
  4. The call() function accepts an object list of a function, while the apply() function accepts a single array of an object.
67. Which of the following code snippets is more efficient, and why?
<script language=”JavaScript”>
for(i=0;i<document.images.length;i++)
document.images[i].src=”blank.gif”;
</script>
<script language=”JavaScript”>
var theimages = document.images;
for(i=0;i<theimages.length;i++)
theimages[i].src=”blank.gif”
</script>
Answers:
  1. Both are equally efficient.
  2. The first code is more efficient as it contains less code.
  3. The first code is more efficient as it employs object caching.
  4. The second code is more efficient as it employs object caching.
68. What is the meaning of obfuscation in JavaScript?
Answers:
  1. Obfuscation is a keyword in JavaScript.
  2. Making code unreadable using advanced algorithms.
  3. Decrypting encrypted source code using advanced algorithms.
  4. None of these.
69. Which of the following JavaScript Regular Expression modifiers finds one or more occurrences of a specific character in a string?
Answers:
  1. ?
  2. *
  3. +
  4. #
70. Which of the following is not a valid JavaScript operator?
Answers:
  1. |
  2. ===
  3. %=
  4. ^
71. Which of the following code snippets returns “[object object]”?
Answers:
  1. <script> var o = new Object(); o.toSource(); </script>
  2. <script> var o = new Object(); o.valueOf(); </script>
  3. <script> var o = new Object(); o.toString(); </script>
  4. <script> var o = new Object(); o.getName(); </script>
72. Which of the following can be used to invoke an iframe from a parent page?
Answers:
  1. window.frames
  2. document.getElementById
  3. document.getelementsbyname
  4. document.getelementsbyclassname
73. Select the following function that shuffles an array?
Answers:
  1. function shuffle(array) { var tmp, current, top = array.length; if(top) while(–top) { current = Math.floor(Math.random() * (top + 1)); tmp = array[current]; array[current] = array[top]; array[top] = tmp; } return array; }
  2. function shuffle(array) { return array.sort(function(a,b) { return (a-b); }); }
  3. function shuffle(array) { var results = new Array(); var sorted_arr = array.sort(); for (var i = 0; i < array.length – 1; i++) { if (sorted_arr[i + 1] == sorted_arr[i]) { results.push(sorted_arr[i]); } } return results; }
  4. function shuffle(array) { for (var tmp, cur, top=array.length; top–;){ cur = (Math.random() * (top + 1)) << 0; tmp = array[cur]; array[cur] = array[top]; array[top] = tmp; } return array.sort(); }
74. Which of the following code snippets removes objects from an associative array?
Answers:
  1. delete array[“propertyName”];
  2. array.propertyName.remove();
  3. array.splice(index, 1);
  4. array[“propertyName”].remove();
75. What is the error in the statement: var charConvert = toCharCode(‘x’);?
Answers:
  1. toCharCode() is a non-existent method.
  2. Nothing. The code will work fine.
  3. toCharCode only accepts numbers.
  4. toCharCode takes no arguments.
76. What value would JavaScript assign to an uninitialized variable?
Answers:
  1. NaN
  2. null
  3. undefined
  4. false
77. What does the following JavaScript code do?
contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
Answers:
  1. It calculates an array’s length.
  2. It compares ‘a’ and ‘obj’ in an array.
  3. The code will cause an error.
  4. It checks if an array contains ‘obj’.
78. If an image is placed styled with z-index=-1 and a text paragraph is overlapped with it, which one will be displayed on top?
Answers:
  1. The paragraph.
  2. The image.
  3. It depends on other rules.
79. Which of the following code snippets gets an image’s dimensions (height & width) correctly?
Answers:
  1. var img = document.getElementById(‘imageid’); var width = img.clientWidth; var height = img.clientHeight;
  2. var img = document.getElementById(‘imageid’); var width = img.width; var height = img.height;
  3. var img = document.getElementById(‘imageid’); var width = img.getAttribute(‘width’); var height = img.getAttribute(‘height’);
  4. var img=document.getElementById(“imageid”); var width=img.offsetWidth; var height=img.offsetHeight;
80. Which of the following are correct values of variableC, and why?
<script>
variableA = [6,8];
variableB =[7,9];
variableC = variableA + variableB;
</script>
Answers:
  1. 6, 7, 8 and 9. The + operator is defined for arrays, and it concatenates strings, so it converts the arrays to strings.
  2. 6, 15 and 9. The + operator is defined for arrays, and it concatenates numbers, so it converts the arrays to numbers.
  3. 6, 8, 7 and 9. The + operator is defined for arrays, and it concatenates strings, so it converts the arrays to strings.
  4. 6, 87 and 9. The + operator is not defined for arrays, and it concatenates strings, so it converts the arrays to strings.
81. The following are the samples for getting a selected value in the from a dropdown list:
<select id=”ddlViewBy”>
<option value=”1″>test1</option>
<option value=”2″ selected=”selected”>test2</option>
<option value=”3″>test3</option>
</select>
Which code block is correct?
Answers:
  1. var e = document.getElementById(“ddlViewBy”); var strUser = e.options[e.selectedIndex].text;
  2. var e = document.getElementById(“ddlViewBy”); var strUser = e.options[e.selectedIndex].value;
  3. var e = document.getElementByName(“ddlViewBy”); var strUser = e.options[e.selectedIndex].text;
  4. var e = document.getElementByName(“ddlViewBy”); var strUser = e.options[e.selectedIndex].value;
82. var profits=2489.8237
Which of the following code(s) produces the following output?
output : 2489.824
Answers:
  1. profits.toFixed(4)
  2. profits.toFixed(3)
  3. profits.formatDollar(3)
  4. profits.nuberFormat(3)
83. A form contains two fields named id1 and id2. How can you copy the value of the id2 field to id1?
Answers:
  1. document.forms[0].id1.value=document.forms[0].id2.value
  2. document.forms[0].id2.value=document.forms[0].id1.value
  3. document.id1.value=document.id2.value
  4. document.id2.value=document.id1.value
84. Which of the following code snippets will toggle a div element’s background color?
<button id=”toggle”>Toggle</button>
<div id=”terd”>Change Background Color.</div>
Answers:
  1. <script> var button = document.getElementById(‘toggle’); button.click = function() { terd.style.backgroundColor = terd.style.backgroundColor == ‘blue’ ? ‘red’ : ‘blue’; }; </script>
  2. <script> var button = document.getElementById(‘toggle’); button.ready = function() { terd.style.backgroundColor = terd.style.backgroundColor == ‘blue’ ? ‘red’ : ‘blue’; }; </script>
  3. <script> var button = document.getElementById(‘toggle’); button.focus = function() { terd.style.backgroundColor = terd.style.backgroundColor == ‘blue’ ? ‘red’ : ‘blue’; }; </script>
  4. <script> var button = document.getElementById(‘toggle’); button.onclick = function() { terd.style.backgroundColor = terd.style.backgroundColor == ‘blue’ ? ‘red’ : ‘blue’; }; </script>
85. How can the user’s previously navigated page be determined using JavaScript?
Answers:
  1. It is not possible in JavaScript. This can be done only through server-side scripting.
  2. Using the document.referrer property
  3. Using the window object
  4. None of these
86. Which of the following is not a valid method for looping an array?
Answers:
  1. var a= [1,2]; for (var i = 0; i < a.length; i++) { alert(a[i]); }
  2. var a= [1,2]; a.forEach( function(item) { alert(item); })
  3. var a= [1,2]; a.map( function(item) { alert(item); })
  4. var a= [1,2]; a.loop( function(item) { alert(item); })
87. Which of the following correctly sets a class for an element?
Answers:
  1. document.getElementById(elementId).className = “Someclass”;
  2. document.getElementById(elementId).setAttribute(“className”, “Someclass”);
  3. document.getElementById(elementId).class = “Someclass”;
  4. document.getElementById(elementId).style = “Someclass”;
88. An HTML form contains 10 checkboxes all named “chkItems”. Which JavaScript function can be used for checking all the checkboxes together?
Answers:
  1. function CheckAll() { for (z = 0; z < document.forms.chkItems.length; z++) { document.forms.chkItems[z].checked=true } }
  2. function CheckAll() { for (z = 0; z < document.forms[0].chkItems.length; z++) { document.forms[0].chkItems[z].checked=true } }
  3. function CheckAll() { for (z = 0; z < document.forms[0].chkItems.length; z++) { document.forms[0].chkItems.list[z].checked=true } }
  4. function CheckAll() { for (z = 0; z < document.forms[0].chkItems.length; z++) { document.forms[0].chkItems.list[z].checked=false } }
89.Which of the following is not a valid Date Object method in JavaScript?
Answers:
  1. parse()
  2. setDay()
  3. setTime()
  4. valueOf()
90.Which event can detect when the user highlights text within a text or textarea object?
Answers:
  1. onSelect()
  2. onBlur
  3. onChange()
  4. onMove
  5. None of these
91.Consider the following code snippet:
var myJSONObject =
{«ircEvent»: «PRIVMSG», «method»: «newURI», «regex»: «^http://.*»};
What is the best way to remove the property ‘regex’, so the result would be this code snippet?
myJSONObject ==
{«ircEvent»: «PRIVMSG», «method»: «newURI»};
Answers:
  1. myJSONObject.regex.delete;
  2. myJSONObject.regex.remove;
  3. delete myJSONObject.regex;
  4. remove myJSONObject.regex;
92.Which of the following is the best way to show both single and double quotes in the same sentence
Answers:
  1. alert(«It’s «+’»game»‘+» time.»);
  2. alert(‘It\’s \»game\» time.’);
  3. alert(‘It\’\s «game» time.’);
  4. alert(‘It\’s «game» time.’);
93.Which of the following statements is true regarding importing JavaScript files inside of other JavaScript files?
Answers:
  1. There is no import/include/require keyword in JavaScript, but there ways to import JS files inside of other JS files.
  2. There is an import keyword in JavaScript, which allows importing JS files inside of other JS files.
  3. There is no option to do so in JavaScript.
94. Which of the following shortcuts can be used for writing multiple document.write statements?
Answers:
  1. for(document){}
  2. with(document) {}
  3. withThis(document){}
  4. None of these
95.In JavaScript, the encodeURI() function is used to encode special characters. Which of the following special characters is/are an exception to that rule?
A. £
B. €
C. @
D. $
Answers:
  1. A
  2. B
  3. C
  4. D
  5. A and B
  6. C and D
96.Consider the following code:
<form>
<textarea id=»foo» name=»foo»></textarea>
</form>
Which of the following is the best method to get the line number of the form’s text area?
Answer:
  1. A<script> foo.value.split(/\r\n\|\r\|\n/g); </script>
  2. <script> foo.value.split(/\r\/n\|\r\|\n/g); </script>
  3. <script> foo.value.split(/\rn\|\r\|\n/g); </script>
  4. <script> foo.value.split(/\r\n|\r|\n/g); </script>
97.Consider the following code:
var setter=new Object()
setter.color=»blue»
How would you delete the color property of the variable seter?
Answer:
  1. setter.color delete;
  2. delete setter.color
  3. delete(setter.color)
  4. setter.color.delete
98. Is the following statement regarding expression closures in JavaScript true or false?
The syntax function(x) {return x*x;} can be written as function(x) x*x.
Answer:
  1. Yes
  2. No
99.Which of the following statements regarding this String prototype is correct?
String.prototype.doSomething = function(suffix) {
return this.indexOf(suffix, this.length — suffix.length) !== -1;
};
Answer:
  1. This method determines whether or not a string ends with another string.
  2. This method determines whether or not a string begins with another string.
  3. This method returns the position of the last occurrence of a specified value in a string.
  4. This method returns the position of the first occurrence of a specified value in a string.
100.What will be the result of the following code?
document.getElementById(“banana”).className = document.getElementById(“banana”).className.replace(/(?:^|\s)apple(?!\S)/g ,’e’ );
Answer:
  1. Replace class ‘apple’ with ‘g’ in the HTML element which contains ID ‘banana’
  2. Replace current class with ‘apple’ in the HTML element which contains ID ‘banana’
  3. Replace class ‘apple’ with ‘e’ in the HTML element which contains ID ‘banana’
  4. Replace ID ‘apple’ with ‘banana’ in the HTML element which contains ID ‘banana’ and class ‘g’
101.Which of the following will determine if the user’s browser is named “Netscape”?
Answer:
  1. if(appName==”Netscape”){}
  2. if(document.appName==”Netscape”){}
  3. if(navigator==”Netscape”){}
  4. if(browser==”Netscape”){}
  5. None of these
102. Given a p element with some text content, which of the following code snippets sets the background color of the text to yellow, its color to red, and its font size to 20px?
Answer:
  1. var p = document.getElementById(elementId);
    p.setAttribute(«style», «background-color:yellow;color:red;font-size:20px;»);
  2. var p = document.getElementById(elementId);
    p.style.background = ‘yellow’;
    p.style.color= ‘red’;
    p.style.size= ’20px’;
  3. var p = document.getElementById(elementId);
    p.style.background = ‘yellow’;
    p.style.color= ‘red’;
    p.style.font.size= ’20px’;
  4. var p = document.getElementById(elementId);
    p.setAttribute(«style», «background-color:red;color:yellow;font-size:20;»);
103.Which of the following are not valid HTML events?
Answer:
  1. onmouseover
  2. onmouseout
  3. onmouseabove
  4. onmousedown
  5. onmousein
104.Which of the following options is used to access the attributes in E4X?
Answer:
  1. @
  2. ::
  3. #
  4. *
105.Which of the following can be used to write a JavaScript function that will accept user input?
Answer:
  1. The prompt method
  2. The alert method
  3. A form field
  4. All of these
106.Which of the following prints «AbBc»?
Answer:
  1. var b = ‘a’; var result = b.toUpperCase() + ‘b’ + ‘b’.toUpperCase() +’C'[‘toLowerCase’](); alert(result);
  2. var b = ‘a’; var result = b.toUpperCase() + ‘b’ + ‘b’.toUpperCase() +’C'[‘toLowerCase’](); alert(result);
  3. var b = ‘a’; var result = b.toUpperCase() + b + ‘b’.toUpperCase() +’C'[‘toLowerCase’](); alert(result);
  4. var b = ‘a’; var result = b.toUpperCase() + ‘b’ + ‘b’.toUpperCase() +C; alert(result);
107.Which of these options is the most maintainable way to attach JavaScript functionality to an HTML element?
Answer:
  1. <p onclick=»alert(‘You clicked me!’)»> some text </p>
  2. <script> function fun(){alert(‘You clicked me!’)} </script>
    <a onclick=fun()>…</a>
  3. <script>
    function fun(){ alert(‘You clicked me!’); };
    var el = document.getElementById(«click-target»);
    el.onClick = fun;
    </script>
    <a id=»click-target»>…</a>
  4. <a href=»javascript:alert(‘You clicked me!’)»>…</a>
108.Which of these options is the most maintainable way to attach JavaScript functionality to an HTML element?
<html>
<body>
<script type=»text/javascript»>
function validate() {
var chk=»ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz»;
var ok=»yes»;
var temp;
var field1=document.getElementById(«t1»);
var field=field1.value.substring(field1.value.length-1,field1.value.length);
if(chk.indexOf(field)==»-1″) {
alert(«error»);
field1.value=(field1.value).slice(0,field1.value.length-1);
}
}
</script>
<input type=»text» id=»t1″ onkeyup=»validate()» onkeypress =»validate()»/>
</body>
</html>
Answer:
  1. The code will cause an error alert to be displayed if a numeric character is entered, and the numeric character is removed.
  2. The code will cause an error alert to be displayed if a non-numeric character is entered, and the non-numeric character is removed.
  3. The code will cause an error alert to be displayed if a numeric character is entered, and the value of textbox is reset.
  4. The code will cause an error alert to be displayed if a non-numeric character is entered, and the value of textbox is reset.
109. What would be the default setting for the expires attribute of the document.cookie property?
Answers:
  1. The duration of the browser session
  2. The duration the current document stays loaded
  3. Twenty-four hours from the time the cookie is set
  4. There is no default setting
  5. The duration for which the machine is on
110.Which of the following choices will remove a selection option from the code below?
<button id”newbtn” onclick=”g();”>Remove</button>
<select name=”selectBox” id=”selectBox”>
<option value=”option1″>option1</option>
<option value=”option2″>option2</option>
<option value=”option3″>option3</option>
<option value=”option4″>option4</option>
</select>
Answers:
  1. <script>
    function g(){
    var index = 1;
    var d = document.getElementById(“selectBox”);
    var d_nested = d.childNodes[index];
    var throwawayNode = d.deleteChild(d_nested);
    }
    </script>
  2. ><script>
    function g(){
    var index = 1;
    var d = document.getElementById(“selectBox”);
    var d_nested = d.childNodes[index];
    var throwawayNode = d.clearChild(d_nested);
    }
    </script>
  3. <script>
    function g(){
    var index = 1;
    var d = document.getElementById(“selectBox”);
    var d_nested = d.childNodes[index];
    var throwawayNode = d.emptyChild(d_nested);
    }
    </script>
  4. <script>
    function g(){
    var index = 1;
    var d = document.getElementById(“selectBox”);
    var d_nested = d.childNodes[index];
    var throwawayNode = d.removeChild(d_nested);
    }
    </script>
111.Which of the following is incorrect regarding Strict mode in JavaScript?
Answer:
  1. It catches some common coding errors, throwing exceptions.
  2. It enables features that are confusing or poorly thought out.
  3. It prevents, or throws errors, when relatively «unsafe» actions are taken (such as gaining access to the global object).
112. Which of the following is incorrect regarding Strict mode in JavaScript?
var a = ‘A’.charCodeAt(0) + 5;
var b = ‘c’.charCodeAt(0) + 1;
var c = 0;
for (var i = 0; i < 10; i++) {
c = c + (a+b % 2);
}
alert(c);
Answer:
  1. 700
  2. 60
  3. 0
  4. 760
113. Which of the following is/are true regarding JavaScript and multi-threading/concurrency?
Answer:
  1. JavaScript is single-threaded, forcing asynchronous events to a queue to wait for execution.
  2. JavaScript is multi-threaded, and behaves in a synchronous manner.
  3. JavaScript can be single or multi-threaded, depending on the browser’s capabilities.
  4. None of these.
114. Which of the following will change the color of the text box to green, as long as the user is pressing a key?
Answer:
  1. input type=»text» onkeydown=»color(‘white’)» onkeyup=»color(‘green’)» name=»txtName»
  2. input type=»text» onkeydown=»color(‘green’)» onkeyup=»color(‘white’)» name=»txtName»
  3. input type=»text» onkeydown=»color(‘green’)» name=»txtName»
  4. input type=»text» onkeydown=»color(‘white’)» name=»txtName»
  5. input type=»text» onkeypress=»color(‘green’)» onkeyup=»color(‘white’)» name=»txtName»
115. In an HTML page, the form tag is defined as follows:
<form onsubmit=»return Validate()»
action=»http://www.mysite.com/»>
The validate() function is intended to prevent the form from being submitted if the name field in the form is empty. What should the validate() function look like?
Answer:
  1. <script type=»text/javascript»> function Validate() { if(document.forms[0].name.value == «») return true; else return false; } </script>
  2. <script type=»text/javascript»> function Validate() { if(document.forms[0].name.value == «») return false; else return true; } </script>
  3. script type=»text/javascript»> function Validate() { if(document.forms[0].name== «») return false; else return true; } </script>
  4.  <script type=»text/javascript»> function Validate() { if(document.forms[0].name == «») return true; else return false; } </script>
116. Which of the following statements are true regarding the code below?
<script>
alert(«foo» === new String(«foo»)); // output false
</script>
Answer:
  1. The «===» operator always returns false.
  2. The «===» operator returns true only if they refer to the same object (comparing by reference) and if both the primitive and the object have the same value.
  3. The «===» operator returns true only if the object (comparing by reference) and the primitive have the same value.
  4. The «===» operator does not work for objects.
117.Which of the following statements are true regarding the «this» keyword in JavaScript?
Answer:
  1. The value of «this» can be set by assignment during execution, and it will be the same each time the function is called.
  2. Inside a function, the value of «this» depends on how many times the function is called.
  3. Inside a function, the value of «this» depends on how the function is called (as a simple call, an object method, a constructor, etc.).
  4. In strict mode, the value of «this» may change from whatever it is set to, when entering the execution context.
118.Which of the following is not a correct way to empty the array a?
Answer:
  1. a = new Array();
  2. a = [];
  3. a.splice(0,a.length);
  4. a.clear()
119.Which of the following is the correct way to resize an iframe based on content?
Answer:
  1. function resizeIframe(height)
    {document.getElementById(‘frame_name_here’).height = parseInt(height)+60;}
    <iframe id=’frame_name_here’ src=’src.htm’></iframe>
  2. function resizeIframe(height)
    {document.getElementByName(‘frame_name_here’).height = parseInt(height)+60;}
    <iframe id=’frame_name_here’ src=’src.htm’></iframe>
  3. function resizeIframe(height)
    {document.getElementByDivId(‘frame_name_here’).height = parseInt(height)+60;}
    <iframe id=’frame_name_here’ src=’src.htm’></iframe>
  4. None of these
120.Which of the following is not a valid JavaScript function?
Answers:
  1. apply()
  2. call()
  3. toString()
  4. All the other options are valid.
121.What does the following code snippet do?
<input type=»radio»name=»r1″value=»radio1″onclick=»this.checked=false;alert(‘sorry’)»>
Answers:
  1. The code is invalid.
  2. The code makes it necessary for the user to select the radio button.
  3. The code disables the radio button.
  4. The code displays an alert when the user selects the button.
122.How can properties be added to an object class?
Answers:
  1. With the prototype() method
  2. With the prototype property
  3. It cannot be done.
  4. With the «this» object
123.Which of the following will correctly check if an object is an array?
Note: There may be more than one right answer.
Answers:
  1. Object.prototype.toString.call(arr) === ‘[object Array]’
  2. Object.isArray(arr)
  3. None of these
  4. With the «this» object
124.Which of the following check if an object has a specific property?
Answers:
  1. hasOwnProperty()
  2. hasProperty()
  3. It is browser-dependent
  4. None of these
125. Given the following window.open function:
window.open(url,name,»attributes»)
How can it be ensured that different URLs are opened in the same window?
Answers:
  1. The second attribute, name, should be the same.
  2. The name attribute should be null.
  3. The name attribute should be omitted.
  4. The name attribute should be different.
  5. None of these.
126.Which of the following code snippets renders a button invisible?
Answers:
  1. var button = document.getElementById(‘buttonId’);
    button.style.display=’none’
  2. var button = document.getElementById(‘buttonId’);
    button.style.display=’block’
  3. var button = document.getElementById(‘btn’);
    button.style.visibility=’false’;
  4. var button = document.getElementById(‘btn’);
    button.style.visibility=’disabled’;
  5. None of these.
127. Why does (0 < 5 < 3) return true?
Answers:
  1. Order of operations produces (true < 3), which returns true.
  2. Order of precedence produces (true < 3), which returns true.
  3. Order of operations produces (false < 3), which returns true.
  4. None of these.
128. What is the cleanest, most effective way to validate decimal numbers in JavaScript?
Answers:
  1. IsNumeric()
  2. isNaN()
  3. valid()
  4. isDecimal()
129. Which of the following is the best reason for not using «for…in» with array iteration?
Answers:
  1. for..in should be used to iterate over an array where index order is important.
  2. for..in should not be used to iterate over an array where index order is important.
  3. for…in loops iterate over non–enumerable properties.
  4. for…in loops do not iterate over enumerable properties.
130. Which of the following is the best reason for not using «for…in» with array iteration?
Answers:
  1. It forces the parser to treat the + sign as a part of an expression.
  2. The + sign is used as a cast operator.
  3. It is used to denote a type of object in JavaScript.
  4. None of these.
131.Which of the following will implement a singleton pattern in JavaScript?
Answers:
  1. <script>
    var anObject = {
    method1: function () {
    // …<
    },
    method2: function () {
    // …
    }
    };
    ></script>
  2. <script>
    function method1(){
    // …
    }
    function method2(){
    // …
    }
    </script>
  3. <script>
    var method1 = function(){
    // …
    }
    var method2 = function(){
    // …
    }
    </script>
  4. <script>
    var method1;
    var method2;
    </script>
132. Which of the following code snippets will correctly detect a touchscreen device?
Answers:
  1. function isTouchDevice() {
    return !!(‘ontouchstart’ in window) || !!(‘onmsgesturechange’ in window);
    };
  2. function isTouchDevice() {
    try {
    document.body.createEvent(«TouchEvent»);
    return true;
    } catch (e) {
    return false;
    }
    }
  3. function isTouchDevice(){
    return (typeof(navigator.ontouchstart) != ‘undefined’) ? true : false;
    }
  4. function isTouchDevice(){
    return (navigator.msMaxTouchPoints == 0);
    }
133. Which of the following shows examples of valid auto increment/decrement loops?
Answers:
  1. for(var i=0; i < 100; i++){} for(var i=0; i > -100; i—){}
  2. for(var i=0; i < 100; i+){} for(var i=0; i > -100; i-){}
  3. for(var i=0; i > 100; i++){}
    for(var i=0; i < -100; i—){}
  4. for(var i=0; i > 100; i+){}
    for(var i=0; i < -100; i-){}
134. Analyze the following code snippet. What will be the output of this code?
<html>
<body>
<script type=»text/javascript»>
var str = «The drain of the plane is plain»;
var patt1 =/ain/g;
document.write(str.match(patt1));
</script>
</body>
</html>
Answers:
  1. a
  2. ain
  3. 7,29
  4. 7
  5. ain,ain
135.The following are sample codes on how to merge properties of two JavaScript objects dynamically:
var obj1 = { food: ‘pizza’, car: ‘ford’ }
var obj2 = { animal: ‘dog’ }
Which of the following are JavaScript codes?
Answer:
  1. obj1.merge(obj2);
  2. function MergeRecursive(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
    }
  3. function MergeRecursive(obj1, obj2) {
    for (var p in obj2) {
    try {
    // Property in destination object set; update its value.
    if ( obj2[p].constructor==Object ) {
    obj1[p] = MergeRecursive(obj1[p], obj2[p]);
    } else {
    obj1[p] = obj2[p];
    }
    } catch(e) {
    // Property in destination object not set; create it and set its value.
    obj1[p] = obj2[p];}
    }
    return obj1;
    }
  4. Object.extend = function(destination,source) {
    for (var property in source)
    destination[property] = source[property];
    return destination;
    }
    obj1.extend(obj2)
136.You need to be able to determine which page of the web site has been the most recently modified. Which object would enable you to do this?
Answers:
  1. document
  2. window
  3. history
  4. browser
  5. form
  6. location
137.Which of the following are the valid JavaScript codes to obtain the number of milliseconds since the epoch?
Note: There may be more than one right answer.
Answers:
  1. var timestamp = new Date().getTime();
  2. var timestamp = Number(new Date());
  3. var timestamp = Date.now;
  4. var timestamp = new Date().valueOf();
138.Which of the following ‘if’ statements is correctly used to get the size of both ‘variable1’ and ‘variable2’ objects?
var variable1 = {‘name’:’theName’, ‘address’:’theAddress’,’age’: ’18’}
var variable2 = [‘theName’,’theAddress’,’18’];
variable1[«name»] = «theName2»;
variable1[«name»] = «theName3»;
variable1[«name2»] = «theName4»;
variable1[«name2»] = «theName5»;
Object.size = function(importer) {
var exporter = 0, key;
for (key in importer) {
if (importer.hasOwnProperty(key)) exporter++;
}
return exporter;
};
Answers:
  1. if(typeof(variable1)==’object’ && typeof(variable2)==’array’){
    Object.size(variable1);
    variable2.length;
    }
  2. if(typeof(variable1)==’array’ && typeof(variable2)==’object’){
    Object.size(variable1);
    variable2.length;
    }
  3. if(typeof(variable1) > typeof(variable2)){
    Object.size(variable1);
    variable2.length;
    }
  4. if(typeof(variable1) == typeof(variable2)){
    Object.size(variable1);
    variable2.length;
    }
139.Consider the following JavaScript arrays:
var a = [1, 2];
var b = [3, 4, 5];
Which of the following will append the contents of array «b» to array «a»?
Answers:
  1. a.push(b);
  2. a.splice(0,0,b);
  3. a = b.concat(a);
  4. a.join(b);
140.How can it be determined if JavaScript is disabled in the user’s browser?
Answers:
  1. It is browser-dependent.
  2. There is no way to detect if JavaScript is disabled.
  3. Use the HTML<noscript> tag to display different content if JavaScript is disabled.
  4. None of these.
141.Which of the following choices shows the correct result for the code below? var arr = []; arr[0] = «Jani»; arr[1] = «Hege»; arr[2] = «Stale»; arr[3] = «Kai Jim»; arr[4] = «Borge»; console.log(arr.join()); arr.splice(2, 0, «Lene»); console.log(arr.join());
Answers:
  1. Jani,Hege,Stale,Kai Jim,Borge
    Lene,Jani,Hege,Stale,Kai Jim,Borge
  2. Jani,Hege,Stale,Kai Jim,Borge
    Jani,Hege,Lene,Stale,Kai Jim,Borge
  3. Jani,Hege,Stale,Kai Jim,Borge
    Jani,Hege,Stale,Kai Jim,Lene,Borge
  4. Jani,Hege,Stale,Kai Jim,Borge
    Jani,Hege,Stale,Kai Jim,Borge
142. Consider the following scenario:
The document.write() method is embedded to write some text within a pair of 
table tags. Upon loading the file, however, garbled text appears on the section of the page where the text should be. What could be the reason for this?
Answers:
  1. The browser does not support JavaScript.
  2. An older version of the browser is being used.
  3. The browser does not support cookies.
143. What is the output of the following code?
var a = 5;
var b = 1;
if(!!»false») {
a = a + 5;
b = 3;
};
if(!!0) {
a = a + 5;
b = b + 2;
};
alert(a+b);
Answers:
  1. 20
  2. 6
  3. None of these
144.Consider the following code:
var vNew=new Date()
Which of the following options will return true?
Answers:
  1. vNew instanceof boolean
  2. vNew instanceof boolean
  3. vNew instanceof Date
  4. All of these
145.Which of the following will detect if the browser supports a certain CSS property?
Answers:
  1. typeof document.body.style.borderRadius == ‘string’
  2. typeof document.body.style.borderRadius == ‘undefined’
  3. typeof document.body.style.borderRadius == true
  4. It is impossible.
146.Which of the following is not a valid code for redirect to stackoverflow.com?
Note: There may be more than one right answer.
Answers:
  1. window.location.href = «http://stackoverflow.com»;
  2. window.location.href («http://stackoverflow.com»);
  3. window.location.replace=»http://stackoverflow.com»;
  4. window.location.replace(«http://stackoverflow.com»);
147.The following statements show two ways of calling a JavaScript function:
i)onclick = «a();»
ii)onclick=»JavaScript:a();»
Which of the following options is correct, with regard to the two statements above?
Answers:
  1. There is no difference between the two statements
  2. The first statement is incorrect and the second one is correct.
  3. The first statement is correct and the second statement is incorrect.
148.Which of the following code snippets will trigger an input type=»file» attribute when an element with a «newbtn» ID is clicked?
Answers:
<button id»newbtn» onclick=»grt();»>Upload</button>
<form>
<input id=»thisId» type=»file» name=»upload» />
</form>
</form>
  1. function grt(){document.getElementById(‘thisId’).keypress();}
  2. function grt(){document.getElementById(‘thisId’).load();}
  3. function grt(){document.getElementById(‘thisId’).dblclick();}
  4. function grt(){document.getElementById(‘thisId’).click();}
149.Which of the following JavaScript code snippets is the more efficient and why?
Code Snippet 1
<script language=»javascript»>
for(i=0;i<document.images.length;i++)
document.images[i].src=»blank.gif»;
</script>
Code Snippet 2
<script language=»javascript»>
var theimages = document.images;
for(i=0;i<theimages.length;i++)
theimages[i].src=»blank.gif»;
</script>
Answers:
  1. Both codes are equally efficient.
  2. The first code is more efficient because it contains less code.
  3. The first code is more efficient because it employs object caching.
  4. The second code is more efficient because it employs object caching.
150.Which of the following cope samples will correctly search for the word «for» in a string?
Note: There may be more than one right answer.
Answers:
  1. var str=»This is test for javascript search !!!»;
    if(str.search(«for») != -1) {
    alert(«true»);
    }
    else {
    alert(«false»);
    }
  2. var str=»This is test for javascript search !!!»;
    if(str.indexof(«for») != -1) {
    alert(«true»);
    }
    else {
    alert(«false»);
    }
  3. var str=»This is test for javascript search !!!»;
    if(str.indexOf(«for») != -1) {
    alert(«true»);
    }
    else {
    alert(«false»);
    }
  4. var str=»This is test for javascript search !!!»;
    if(str.contains(«for») != -1) {
    alert(«true»);
    }
    else {
    alert(«false»);
    }
151.Given two frames Frame1 and Frame2, where Frame2 has a div element with id «some», how can the div element’s color be changed in Frame2, using JavaScript code in Frame1?
Answers:
  1. var div = top.Frame2.document.getElementById(‘some’);
    div.style.color= «orange»;
  2. var div = document.getElementById(‘some’);
    div.style.color= «orange»;
  3. var div = top.Frame1.document.getElementById(‘some’);
    div.style.color= «orange»;
  4. None of these.
152.Which of the following JavaScript Regular Expression character classes finds any non-digit character in a given string?
Answers:
  1. \W
  2. \S
  3. \B
  4. \D
153. Which best describes void?
Answers:
  1. A method
  2. A function
  3. A statement
  4. An operator
  5. A built-in object
154.Which of the following is used to solve the problem of enumerations in JavaScript?
Answers:
  1. let
  2. Regex
  3. Generators
  4. E4X
155.Which of the following cannot be achieved using JavaScript?
Note: There may be more than one right answer.
Answers:
  1. Read or write from external files (except .js files)
  2. Access or modify browser settings
  3. Launch client processes (eg windows applications)
  4. Launching the default email application of the client
156.The following are sample codes on how to loop through JavaScript object literals with objects as members:
var validation_messages = {
«key_1»: {
«your_name»: «jimmy»,
«your_msg»: «hello world»
},
«key_2»: {
«your_name»: «billy»,
«your_msg»: «foo equals bar»
}
}
Which of the following are invalid native JavaScript codes?
Note: There may be more than one right answer.
Answers:
  1. for (var key in validation_messages) {
    var obj = validation_messages[key];
    for (var prop in obj) {
    alert(prop + » = » + obj[prop]);
    }
    }
  2. Object.keys(validation_messages).forEach(function(key) {
    var obj = validation_messages[key];
    Object.keys(obj).forEach(function(key) {
    alert (prop + “ = “ + obj[key]);
    )};
  3. (validation_messages.hasOwnProperty(key)) {
    var obj = validation_messages[key];
    for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
    alert(prop + “ = “ + obj[prop]);
    }
    }
    }
    }
  4. _.each(validation_messages, function(value, key){
    _.each(value, function(value, key){
    alert(prop + » = » + value);
    });
    });
157.Analyze the following code snippet. What will be the output of this code?
html>
<body>
<script type=»text/javascript»>
var str = «Visit Gardens(now)»;
var patt1 = new RegExp(«(now)», «g»);
patt1.test(str);
document.write(RegExp.lastParen);
</script>
</body>
</html>
Answers:
  1. now
  2. (now)
  3. 15
  4. 19
158.Consider the following code:
var variable=2*2+10000/10-133%5;
Which of the following combinations have the lowest operator precedence in «variable»?
Answers:
  1. «*» and «+»
  2. «/» and «%»
  3. «/» and «+»
  4. «*» and «%»
159.While coding a loop, you come across a condition where you have to terminate the loop and continue with the statements following the loop. Which statement would you use?
Answers:
  1. exit
  2. return
  3. continue
  4. while
  5. break
160. What is the best way to make optional parameters of functions?
Answers:
  1. function someFunction(requiredArg, optionalArg) {
    optionalArg = optionalArg || ‘defaultValue’;
    alert(optionalArg);
    }
  2. function someFunction(requiredArg, optionalArg) {
    optionalArg = (typeof optionalArg === «undefined») ? «defaultValue» : optionalArg;
    alert(optionalArg);
    }
  3. function someFunction(requiredArg, optionalArg) {
    optionalArg = (optionalArg === «undefined») ? «defaultValue» : optionalArg;
    alert(optionalArg);
  4. All of these
161. Which of the following are correct closure functions?
Answers:
  1. function foo(x) {
    var tmp = 3;
    return function (y) {
    alert(x + y + (++tmp));
    }
    }
    var bar = foo(2); // bar is now a closure.
    bar(10);
  2. function foo(x) {
    var tmp = 3;
    function bar(y) {
    alert(x + y + (++tmp));
    }
    bar(10);
    }
    foo(2)
  3. function foo(x) {
    var tmp = 3;
    function bar(y) {
    function bar1(tmp) {
    alert(x + y + (++tmp));
    }
    }
    bar(10);
    }
    foo(2)
  4. function foo(x) {
    var tmp = 3;
    return function (y) {
    alert(x + y + tmp);
    x.memb = x.memb ? x.memb + 1 : 1;
    alert(x.memb);
    }
    }
    var age = new Number(2);
    var bar = foo(age); // bar is now a closure referencing age.
    bar(10);
162.Which of the following will correctly detect browser language preference?
Answers:

      1. var language = window.navigator.userLanguage || window.navigator.language;
        alert(language);
      2. var language = navigator.browserLanguage || window.navigator.language;
        alert(language);
      3. var language =navigator.userLanguage;
        alert(language);
      4. var language = window.navigator.language;
        alert(language);
      163.What is the output of the following code?
      var container = {
      someKey: 3,
      someOtherKey: “someObject”,
      anotherKey: “Some text”
      };
      if (“someOtherKey” in container) {
      alert (true);
      }
      delete container [“someOtherKey”];
      if (container[“someOtherKey”] === null) {
      alert (false);
      }
      if (container[“someOtherKey”] === undefined) {
      alert (true);
      }
      if (container.someOtherKey === undefined) {
      alert (false);
      }
      if (container.someOtherKey === undefined) {
      alert (true);
      }
      delete container[“someKey”];
      if (container.someKey === 3) {
      alert (true);
      }
      Answers:
      1. true
        true
        false
      2. true
        true
        true
      3. true
        false
        true
        false
        true
        true
      4. true
        true
        false
        true
      164. Which of the following is a good reason why JavaScript variables would start with a dollar sign ($)?
      Answers:
      1. $ is a prefix used to create a instance of a object.
      2. $ is a keyword in JavaScript.
      3. $ is used to quickly identify and parse variables
      4. None of these
      165.Which of the following code is correct for validating date values?
      Note: There may be more than one right answer.
      Answers:
      1. var d = Date.parse(‘foo’);
        if (isNaN(d)==false)
        {
        alert(new Date(d));
        } else {
        alert(‘Invalid date’);
        }
      2. var d = new Date(‘foo’);
        if (d instanceof Date && isFinite(d))
        {
        alert(d);
        } else {
        alert(‘Invalid date’);
        }
      3. Date.prototype.valid = function() {
        return isFinite(this);
        }
        var d = new Date(‘foo’);
        if (d.valid())
        {
        alert(d);
        } else {
        alert(‘Invalid date’);
        }
      4. All of the above
      166. Which of the following correctly explains the difference between a «for…in» and a «for» loop?
      Answers:
      1. «for…in» has two expressions. It iterates over the enumerable properties of an object, in an arbitrary order, for each distinct property, statements can be executed. This should not be used to iterate over an array where index order is important.
        «for» consists of three optional expressions enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
      2. «for…in» has three expressions. It iterates over the enumerable properties of an object, in an arbitrary order, for each distinct property, statements can be executed. This should not be used to iterate over an array where index order is important.
        «for» consists of four optional expressions enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
      3. «for…in» iterates over the enumerable properties of an object, in an arbitrary order, for each distinct property, statements can be executed. This should be used to iterate over an array where index order is important.
        «for» consists of three optional expressions enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
      4. «for…in» iterates over the enumerable properties of an object, in arbitrary order, for each distinct property, statements can be executed, this should be used to iterate over an array where index order is important.
        «for» consists of two optional expressions enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
      167.Which of the following will list the properties of a JavaScript object?
      Answers:
      1. var keys = Object.keys(myJsonObject);
      2. var keys = Object.value(myJsonObject)
      3. var keys = Object.keys(myJsonValue)
      4. None of these

No comments:

Post a Comment