Skip to main content

Javascript Test Upwork Answers 2019

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

• body onload=»message()»
• body onunload=»message()»
• body onsubmit=»message()»
• body onreset=»message()»

2. Which of the following is not a valid method in generator-iterator objects in JavaScript?

Answers:

• send()
• throw()
• next()
• stop()

3. How can created cookies be deleted using JavaScript?

Answers:

• They can’t be deleted. They are valid until they expire.
• Overwrite with an expiry date in the past
• Use escape() on the value of the path attribute
• Use unescape() on the value of the path attribute
• The cookie file will have to be removed from the client machine.
• Wait till the expiry date is reached

4. Which of the following JavaScript Regular Expression modifiers finds one or more occurrences of a specific character in a string?

Answers:

• ?
• *
• +
• #

5. Which of the following is not a valid Date Object method in JavaScript?

Answers:

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

• reduce()
• reduceRight()
• reverse()
• pop()

7. When setting cookies with JavaScript, what will happen to the cookies.txt data if the file exceeds the maximum size?

Answers:

• The script automatically generates a run-time error.
• The script automatically generates a load-time error.
• All processes using document.cookie are ignored.
• The file is truncated to the maximum length.

8. Which of the following can be used for disabling the right click event in Internet Explorer?

Answers:

• event.button == 2
• event.button == 4
• event.click == 2
• event.click == 4

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

• <script> var button = document.getElementById(‘toggle’); button.click = function() { terd.style.backgroundColor = terd.style.backgroundColor == ‘blue’ ? ‘red’ : ‘blue’; }; </script>
• <script> var button = document.getElementById(‘toggle’); button.ready = function() { terd.style.backgroundColor = terd.style.backgroundColor == ‘blue’ ? ‘red’ : ‘blue’; }; </script>
• <script> var button = document.getElementById(‘toggle’); button.focus = function() { terd.style.backgroundColor = terd.style.backgroundColor == ‘blue’ ? ‘red’ : ‘blue’; }; </script>
• <script> var button = document.getElementById(‘toggle’); button.onclick = function() { terd.style.backgroundColor = terd.style.backgroundColor == ‘blue’ ? ‘red’ : ‘blue’; }; </script>

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

• input name=txtId type=»text» onreset=»return ValidateField()»
• input name=txtId type=»text» onfocus=»return ValidateField()»
• input name=txtId type=»text» onsubmit=»return ValidateField()»
• input name=txtId type=»text» onblur=»return ValidateField()»

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

• firststep1second
• step1step2
• step1
• step1step2step3

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

• logo.source=»companylogo2.gif»
• logo.source=»companylogo1.gif»
• document.getElementById(‘logo’).src=»companylogo1.gif»
• document.getElementById(‘logo’).src=»companylogo2.gif»

13. Which of the following are correct values of variableC, and why?

<script>
variableA = [6,8];
variableB =[7,9];
variableC = variableA + variableB;
</script>

Answers:

• 6, 7, 8 and 9. The + operator is defined for arrays, and it concatenates strings, so it converts the arrays to strings.
• 6, 15 and 9. The + operator is defined for arrays, and it concatenates numbers, so it converts the arrays to numbers.
• 6, 8, 7 and 9. The + operator is defined for arrays, and it concatenates strings, so it converts the arrays to strings.
• 6, 87 and 9. The + operator is not defined for arrays, and it concatenates strings, so it converts the arrays to strings.

14. Which of the following determines whether cookies are enabled in a browser or not?

Answers:

• (navigator.Cookie)? true : false
• (application.cookieEnabled)? true : false
• (navigator.cookieEnabled)? true : false
• (application.cookie)? true : false

15. Which of the following modifiers must be set if the JavaScript lastIndex object property was used during pattern matching?

Answers:

• i
• m
• g
• s

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

• document.getElementById(‘ERImage’).src=»Image1.jpg»
• document.getElementById(‘ERImage’).src=»Image2.jpg»
• document.getElementById(‘ERImage’).style.src=»Image1.jpg»
• document.getElementById(‘ERImage’).style.src=»Image2.jpg»

17. Which of the following is true about setTimeOut()?

Answers:

• The statement(s) it executes run(s) only once.
• It pauses the script in which it is called.
• clearTimeOut() won’t stop its execution.
• The delay is measured in hundredths of a second.
• It is required in every JavaScript function.

18. Which of the following objects in JavaScript contains the collection called «plugins»?

Answers:

• Location
• Window
• Screen
• Navigator

19. Which of following uses the «with» statement in JavaScript correctly?

Answers:

• with (document.getElementById(«blah»).style) { background = «black»; color = «blue»; border = «1px solid green»; }
• with document.getElementById(«blah»).style background = «black»; color = «blue»; border = «1px solid green»; End With
• With document.getElementByName(«blah»).style background = «black»; color = «blue»; border = «1px solid green»; End With
• with (document.getElementById(«blah»).style) { .background = «black»; .color = «blue»; .border = «1px solid green»; }

20. Which event can detect when the user highlights text within a text or textarea object?

Answers:

• onSelect
• onBlur
• onChange
• onMove
• None of these

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

• myJSONObject.regex.delete;
• myJSONObject.regex.remove;
• delete myJSONObject.regex;
• remove myJSONObject.regex;

22.Which of the following is the best way to show both single and double quotes in the same sentence?

Answers:

• alert(«It’s «+'»game»‘+» time.»);
• alert(‘It\’s \»game\» time.’);
• alert(‘It\’\s «game» time.’);
• alert(‘It\’s «game» time.’);

23. Which of the following statements is true regarding importing JavaScript files inside of other JavaScript files?

Answers:

• There is no import/include/require keyword in JavaScript, but there ways to import JS files inside of other JS files.
• There is an import keyword in JavaScript, which allows importing JS files inside of other JS files.
• There is no option to do so in JavaScript.

24. Which of the following shortcuts can be used for writing multiple document.write statements?

Answers:

• for(document){}
• with(document) {}
• withThis(document){}
• None of these

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

• A
• B
• C
• D
• A and B
• C and D

26. 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?

Answers:

• <script> foo.value.split(/\r\n\|\r\|\n/g); </script>
• <script> foo.value.split(/\r\/n\|\r\|\n/g); </script>
• <script> foo.value.split(/\rn\|\r\|\n/g); </script>
• <script> foo.value.split(/\r\n|\r|\n/g); </script>

27. Which of the following code snippets shows an alert for an empty string?

var a = «»;

Answers:

• If(a){ alert(‘This is empty string’);}
• If(a == NUL){ alert(‘This is empty string’);}
• If(!a){ alert(‘This is empty string’);}
• If(a.empty){ alert(‘This is empty string’);}

28. Consider the following code:

var setter=new Object()
setter.color=»blue»

How would you delete the color property of the variable seter?

Answers:

• setter.color delete;
• delete setter.color
• delete(setter.color)
• setter.color.delete

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

Answers:

• True
• False

30. 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;
};

Answers:

• This method determines whether or not a string ends with another string.
• This method determines whether or not a string begins with another string.
• This method returns the position of the last occurrence of a specified value in a string.
• This method returns the position of the first occurrence of a specified value in a string.

31. What will be the result of the following code?

document.getElementById(“banana”).className = document.getElementById(“banana”).className.replace(/(?:^|\s)apple(?!\S)/g ,’e’ );

Answers:

• Replace class ‘apple’ with ‘g’ in the HTML element which contains ID ‘banana’
• Replace current class with ‘apple’ in the HTML element which contains ID ‘banana’
• Replace class ‘apple’ with ‘e’ in the HTML element which contains ID ‘banana’
• Replace ID ‘apple’ with ‘banana’ in the HTML element which contains ID ‘banana’ and class ‘g’

32. Which of the following will determine if the user’s browser is named “Netscape”?

Answers:

• if(appName==”Netscape”){}
• if(document.appName==”Netscape”){}
• if(navigator==”Netscape”){}
• if(browser==”Netscape”){}
• None of these

33. 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?

Answers:

• var p = document.getElementById(elementId);
p.setAttribute(«style», «background-color:yellow;color:red;font-size:20px;»);
• var p = document.getElementById(elementId);
p.style.background = ‘yellow’;
p.style.color= ‘red’;
p.style.size= ’20px’;
• var p = document.getElementById(elementId);
p.style.background = ‘yellow’;
p.style.color= ‘red’;
p.style.font.size= ’20px’;
• var p = document.getElementById(elementId);
p.setAttribute(«style», «background-color:red;color:yellow;font-size:20;»);

34. Which of the following are not valid HTML events?

Answers:

• onmouseover
• onmouseout
• onmouseabove
• onmousedown
• onmousein

35. Which of the following options is used to access the attributes in E4X?

Answers:

• @
• ::
• #
• *

36. Which of the following can be used to write a JavaScript function that will accept user input?

Answers:

• The prompt method
• The alert method
• A form field
• All of these

37. How can the operating system of the client machine be detected?

Answers:

• It is not possible using JavaScript.
• Using the navigator object
• Using the window object
• Using the document object
• None of these.

38. Which of the following prints «AbBc»?

Answers:

• var b = ‘a’; var result = b.toUpperCase() + ‘b’ + ‘b’.toUpperCase() +’C'[‘toLowerCase’](); alert(result);
• var b = ‘a’; var result = b.toUpperCase() + ‘b’ + ‘b’.toUpperCase() +’c'[‘toUpperCase’](); alert(result);
• var b = ‘a’; var result = b.toUpperCase() + b + ‘b’.toUpperCase() +’C'[‘toLowerCase’](); alert(result);
• var b = ‘a’; var result = b.toUpperCase() + ‘b’ + ‘b’.toUpperCase() +C; alert(result);

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

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

40. Performance-wise, which is the fastest way of repeating a string in JavaScript?

Answers:

• String.prototype.repeat = function( num ) { return new Array( num + 1 ).join( this ); }
• function repeat(pattern, count) { if (count < 1) return »; var result = »; while (count > 0) { if (count & 1) result += pattern; count >>= 1, pattern += pattern; } return result; }
• 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; };
• String.prototype.repeat = function (n, d) { return —n ? this + (d || ») + this.repeat(n, d) : » + this };

41. Consider the following variable declarations:

var a=»adam»
var b=»eve»

Which of the following would return the sentence «adam and eve»?

Answers:

• a.concatinate(«and», b)
• a.concat(«and», b)
• a.concatinate(» and «, b)
• a.concat(» and «, b)

42. Which of the following code snippets will correctly split «str»?

Answers:

• <script> var str = ‘something — something_else’; var substrn = str.split(‘ — ‘); </script>
• <script> var str = ‘something — something_else’; var substrn = split.str(‘ — ‘); </script>
• <script> var str = ‘something — something_else’; var substrn = str.split(‘ — ‘,’ — ‘); </script>
• <script> var str = ‘something — something_else’; var substrn = split.str(‘ — ‘,’ — ‘); </script>

43. Which object can be used to ascertain the protocol of the current URL?

Answers:

• document
• window
• history
• browser
• form
• location

44. How can a JavaScript object be printed?

Answers:

• console.log(obj)
• console.print(obj)
• console.echo(obj);
• None of these

45. Which of the following is the correct syntax for using the JavaScript exec() object method?

Answers:

• RegExpObject.exec()
• RegExpObject.exec(string)
• RegExpObject.exec(parameter1,parameter2)
• None of these

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

• arr.push(«New Item»)
• arr[arr.length] = «New Item»
• arr.unshift(«New Item»)
• arr.append(«New Item»)

47. Which of the following will check whether the variable vRast exists or not?

Answers:

• if (typeof vRast=»undefined») {}
• if (typeof vRast ==»undefined») {}
• if (vRast.defined =true) {}
• if (vRast.defined ==true) {}

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

• It will force a user to enter only numeric values.
• It will force a user to enter only alphanumeric values.
• It will force a user to enter only English alphabet character values.
• None of these.

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

• document.getElementById(‘ERImage’).src=»Image1.jpg»
• document.getElementById(‘ERImage’).src=»Image2.jpg»
• document.getElementById(‘ERImage’).style.src=»Image1.jpg»
• document.getElementById(‘ERImage’).style.src=»Image2.jpg»

50. Which of the following choices will detect if «variableName» declares a function?

<script>
var variableName= function(){};
</script>

Answers:

• return variableName;
• nameof variableName;
• isFunction variableName;
• typeof variableName;

51. Which of the following choices will change the source of the image to «image2.gif» when a user clicks on the image?

Answers:

• img id=»imageID» src=»image1.gif» width=»50″ height=»60″ onmousedown=»changeimg(image1.gif)» onmouseup=»changeimg(image2.gif)»
• img id=»imageID» src=»image1.gif» width=»50″ height=»60″ onmouseclick=»changeimg(image2.gif)» onmouseup=»changeimg(image1.gif)»
• img id=»imageID» src=»image2.gif» width=»50″ height=»60″ onmousedown=»changeimg(image1.gif)» onmouseup=»changeimg(image2.gif)»
• img id=»imageID» src=»image2.gif» width=»50″ height=»60″ onmousedown=»changeimg(image2.gif)» onmouseup=»changeimg(image1.gif)»
• img id=»imageID» src=»image1.gif» width=»50″ height=»60″ onmousedown=»changeimg(‘image2.gif’)» onmouseup=»changeimg(‘image1.gif’)»

52. Which of these options is the most maintainable way to attach JavaScript functionality to an HTML element?

Answers:

• <p onclick=»alert(‘You clicked me!’)»> some text </p>
• <script> function fun(){alert(‘You clicked me!’)} </script>
<a onclick=fun()>…</a>
• <script>
function fun(){ alert(‘You clicked me!’); };
var el = document.getElementById(«click-target»);
el.onClick = fun;
</script>
<a id=»click-target»>…</a>
• <a href=»javascript:alert(‘You clicked me!’)»>…</a>

53. What does the following JavaScript code do?

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

Answers:

• The code will cause an error alert to be displayed if a numeric character is entered, and the numeric character is removed.
• The code will cause an error alert to be displayed if a non-numeric character is entered, and the non-numeric character is removed.
• The code will cause an error alert to be displayed if a numeric character is entered, and the value of textbox is reset.
• The code will cause an error alert to be displayed if a non-numeric character is entered, and the value of textbox is reset.

54. What would be the default setting for the expires attribute of the document.cookie property?

Answers:

• The duration of the browser session
• The duration the current document stays loaded
• Twenty-four hours from the time the cookie is set
• There is no default setting
• The duration for which the machine is on

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

• <script>
function g(){
var index = 1;
var d = document.getElementById(“selectBox”);
var d_nested = d.childNodes[index];
var throwawayNode = d.deleteChild(d_nested);
}
</script>
• <script>
function g(){
var index = 1;
var d = document.getElementById(“selectBox”);
var d_nested = d.childNodes[index];
var throwawayNode = d.clearChild(d_nested);
}
</script>
• <script>
function g(){
var index = 1;
var d = document.getElementById(“selectBox”);
var d_nested = d.childNodes[index];
var throwawayNode = d.emptyChild(d_nested);
}
</script>
• <script>
function g(){
var index = 1;
var d = document.getElementById(“selectBox”);
var d_nested = d.childNodes[index];
var throwawayNode = d.removeChild(d_nested);
}
</script>

56. Which of the following is incorrect regarding Strict mode in JavaScript?

Answers:

• It catches some common coding errors, throwing exceptions.
• It enables features that are confusing or poorly thought out.
• It prevents, or throws errors, when relatively «unsafe» actions are taken (such as gaining access to the global object).

57. Which of the following best describes a «for» loop?

Answers:

• «for» loop consists of six optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
• «for» loop consists of five optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
• «for» loop consists of four optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
• «for» loop consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.

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

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

59. Which of the following is not a valid HTML event?

Answers:

• ondblclick
• onmousemove
• onclick
• onblink

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

• I
• Is
• s
• I,s,

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

• 10
• 14
• 3
• 7

62. Which of the following are JavaScript unit testing tools?

Answers:

• Buster.js, jQuery, YUI Yeti
• QUnit, Modernizr, JsTestDriver
• Node.js, Modernizr, Jasmine
• Buster.js, YUI Yeti, Jasmine

63. Which of the following correctly uses a timer with a function named rearrange()?

Answers:

• tmr=setTimeout(«rearrange ()»,1)
• tmr=Timer(1,»rearrange ()»)
• tmr=Timer(«rearrange ()»,1)
• tmr=setTimeout(1,»rearrange ()»)

64. Which of the following can be used to escape the ‘ character?

Answers:

• *
• \
• —
• @
• #
• %
• |
• ~

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

• onblur
• onfocus
• lostfocus
• gotfocus
• None of these

66. Which of the following are not global methods and properties in E4X?

Answers:

• ignoreComments
• ignoreWhiteSpace
• setName()
• setNamespace()
• ignoreComments and ignoreWhiteSpace
• setName() and setNamespace()

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

• <p onmouseover=»style.color=’black'» onmouseout=»style.color=’blue'»> The text of the paragraph..</p>
• <p onmouseover=»style.color=’blue'» onmouseout=»style.color=’black'»> The text of the paragraph..</p>
• <p onmouseout=»style.color=’blue'»> The text of the paragraph..</p>
• <p onmouseover=»style.color=’blue'»> The text of the paragraph..</p>
• <p onmousein=»style.color=’blue'» onmouseout=»style.color=’black'»> The text of the paragraph..</p>

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

• It’s invalid JSON code.
• It makes it difficult for a third-party to insert the JSON response into an HTML document with a <script> tag.
• It iterates the JSON response.
• It prevents the JSON response from getting executed.

69. Consider the three variables:

someText = ‘JavaScript1.2’;
pattern = /(\w+)(\d)\.(\d)/i;
outCome = pattern.exec(someText);

What does outCome[0] contain?

Answers:

• true
• false
• JavaScript1.2
• null
• 0

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

• var e = document.getElementById(«ddlViewBy»); var strUser = e.options[e.selectedIndex].text;
• var e = document.getElementById(«ddlViewBy»); var strUser = e.options[e.selectedIndex].value;
• var e = document.getElementByName(«ddlViewBy»); var strUser = e.options[e.selectedIndex].text;
• var e = document.getElementByName(«ddlViewBy»); var strUser = e.options[e.selectedIndex].value;

71. var profits=2489.8237

Which of the following code(s) produces the following output?

output : 2489.824

Answers:

• profits.toFixed(4)
• profits.toFixed(3)
• profits.formatDollar(3)
• profits.nuberFormat(3)

72. A form contains two fields named id1 and id2. How can you copy the value of the id2 field to id1?

Answers:

• document.forms[0].id1.value=document.forms[0].id2.value
• document.forms[0].id2.value=document.forms[0].id1.value
• document.id1.value=document.id2.value
• document.id2.value=document.id1.value

73. How can the user’s previously navigated page be determined using JavaScript?

Answers:

• It is not possible in JavaScript. This can be done only through server-side scripting.
• Using the document.referrer property
• Using the window object
• None of these

74. Which of the following is not a valid method for looping an array?

Answers:

• var a= [1,2]; for (var i = 0; i < a.length; i++) { alert(a[i]); }
• var a= [1,2]; a.forEach( function(item) { alert(item); })
• var a= [1,2]; a.map( function(item) { alert(item); })
• var a= [1,2]; a.loop( function(item) { alert(item); })

75. Which of the following correctly sets a class for an element?

Answers:

• document.getElementById(elementId).className = «Someclass»;
• document.getElementById(elementId).setAttribute(«className», «Someclass»);
• document.getElementById(elementId).class = «Someclass»;
• document.getElementById(elementId).style = «Someclass»;

76. An HTML form contains 10 checkboxes all named «chkItems». Which JavaScript function can be used for checking all the checkboxes together?

Answers:

• function CheckAll() { for (z = 0; z < document.forms.chkItems.length; z++) { document.forms.chkItems[z].checked=true } }
• function CheckAll() { for (z = 0; z < document.forms[0].chkItems.length; z++) { document.forms[0].chkItems[z].checked=true } }
• function CheckAll() { for (z = 0; z < document.forms[0].chkItems.length; z++) { document.forms[0].chkItems.list[z].checked=true } }
• function CheckAll() { for (z = 0; z < document.forms[0].chkItems.length; z++) { document.forms[0].chkItems.list[z].checked=false } }

77. What is the output of the following code?

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

Answers:

• 700
• 60
• 0
• 760

78. Which of the following is/are true regarding JavaScript and multi-threading/concurrency?

Answers:

• JavaScript is single-threaded, forcing asynchronous events to a queue to wait for execution.
• JavaScript is multi-threaded, and behaves in a synchronous manner.
• JavaScript can be single or multi-threaded, depending on the browser’s capabilities.
• None of these.

79. Which of the following is not a valid Date Object method in JavaScript?

Answers:

• parse()
• setDay()
• setTime()
• valueOf()

80. Consider the following JavaScript function to change the color of the text box named txtName:

function color(col) { document.forms[0].txtName.style.background=col }

Which of the following will change the color of the text box to green, as long as the user is pressing a key?

Answers:

• input type=»text» onkeydown=»color(‘white’)» onkeyup=»color(‘green’)» name=»txtName»
• input type=»text» onkeydown=»color(‘green’)» onkeyup=»color(‘white’)» name=»txtName»
• input type=»text» onkeydown=»color(‘green’)» name=»txtName»
• input type=»text» onkeydown=»color(‘white’)» name=»txtName»
• input type=»text» onkeypress=»color(‘green’)» onkeyup=»color(‘white’)» name=»txtName»

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

Answers:

• The call() function accepts an argument list of a function, while the apply() function accepts a single array of arguments.
• The apply() function accepts an argument list of a function, while the call() function accepts a single array of arguments.
• The call() function accepts an object list of a function, while the apply() function accepts a single array of an object.
• The call() function accepts an object list of a function, while the apply() function accepts a single array of an object.

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

• Both are equally efficient.
• The first code is more efficient as it contains less code.
• The first code is more efficient as it employs object caching.
• The second code is more efficient as it employs object caching.

83. What is the meaning of obfuscation in JavaScript?

Answers:

• Obfuscation is a keyword in JavaScript.
• Making code unreadable using advanced algorithms.
• Decrypting encrypted source code using advanced algorithms.
• None of these.

84. Which of the following is not a valid JavaScript operator?

Answers:

• |
• ===
• %=
• ^

85. Which of the following code snippets returns «[object object]»?

Answers:

• <script> var o = new Object(); o.toSource(); </script>
• <script> var o = new Object(); o.valueOf(); </script>
• <script> var o = new Object(); o.toString(); </script>
• <script> var o = new Object(); o.getName(); </script>

86. Which of the following code snippets will correctly get the length of an object?

Answers:

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

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

• <script type=»text/javascript»> function Validate() { if(document.forms[0].name.value == «») return true; else return false; } </script>
• <script type=»text/javascript»> function Validate() { if(document.forms[0].name.value == «») return false; else return true; } </script>
• script type=»text/javascript»> function Validate() { if(document.forms[0].name== «») return false; else return true; } </script>
• <script type=»text/javascript»> function Validate() { if(document.forms[0].name == «») return true; else return false; } </script>

88. Which of the following code snippets changes an image on the page?

Answers:

• var img = document.getElementById(«imageId»); img.src = «newImage.gif»;
• var img = document.getElementById(«imageId»); img.style.src = «newImage.gif»;
• var img = document.getElementById(«imageId»); img.src.value = «newImage.gif»;
• var img = document.getElementById(«imageId»); img = «newImage.gif»;

89. Which of the following results is returned by the JavaScript operator «typeof» for the keyword «null»?

Answers:

• function
• object
• string
• number

90. What will be the final value of the variable «apt»?

var apt=2;
apt=apt<<2;

Answers:

• 2
• 4
• 6
• 8
• 16

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

• lco
• com
• ome
• Welcome

92. Are the two statements below interchangeable?

object.property
object[»property»]

Answers:

• Yes
• No

93. Which of the following code snippets will return all HTTP headers?

Answers:

• var req = new XMLHttpRequest(); req.open(‘GET’, document.location, false); req.send(null); var headers = req.getAllResponseHeaders().toLowerCase(); alert(headers);
• var req = new XMLHttpAccess(); req.open(‘GET’, document.location, false); req.send(null); var headers = req.getAllResponseHeaders().toLowerCase(); alert(headers);
• var req = new XMLHttpRequest(); req.open(‘GET’, document.location, false); req.send(null); var headers = req.getResponseHeader().toLowerCase(); alert(headers);
• var req = new XMLHttpRequestHeader(); req.open(‘GET’, document.location, false); req.send(null); var headers = req.retrieveAllResponseHeaders().toLowerCase(); alert(headers);

94. Which of the following is the most secure and efficient way of declaring an array?

Answers:

• var a = []
• var a = new Array()
• var a = new Array(n)
• var a

95. Select the following function that shuffles an array?

Answers:

• 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; }
• function shuffle(array) { return array.sort(function(a,b) { return (a-b); }); }
• 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; }
• 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(); }

96. Which of the following code snippets removes objects from an associative array?

Answers:

• delete array[«propertyName»];
• array.propertyName.remove();
• array.splice(index, 1);
• array[«propertyName»].remove();

97. What is the error in the statement: var charConvert = toCharCode(‘x’);?

Answers:

• toCharCode() is a non-existent method.
• Nothing. The code will work fine.
• toCharCode only accepts numbers.
• toCharCode takes no arguments.

98. What value would JavaScript assign to an uninitialized variable?

Answers:

• NaN
• null
• undefined
• false

99. Which of the following Regular Expression pattern flags is not valid?

Answers:

• gi
• p
• i
• g

100. Which of the following built-in functions is used to access form elements using their IDs?

Answers:

• getItem(id)
• getFormElement(id)
• getElementById(id)
• All of these

101. Which of the following statements is correct?

Answers:

• There is no undefined property in JavaScript.
• Undefined object properties can be checked using the following code: if (typeof something == null) alert(«something is undefined»);
• It is not possible to check for undefined object properties in JavaScript.
• Undefined object properties can be checked using the following code: if (typeof something === «undefined») alert(«something is undefined»);

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

• bar[‘baz’]();
• object[‘foo’][‘bar’][‘baz’]();
• document[‘foo’][‘bar’][‘baz’]();
• window[‘foo’][‘bar’][‘baz’]();

103. Which of the following options can be used for adding direct support for XML to JavaScript?

Answers:

• E4X
• egex
• Generators and Iterators
• let

104. Which of the following will detect which DOM element has the focus?

Answers:

• document.activeElement
• document.ready
• document.referrer
• document.getelementbyid

105. Which of the following will randomly choose an element from an array named myStuff, given that the number of elements changes dynamically?

Answers:

• randomElement = myStuff[Math.floor(Math.random() * myStuff.length)];
• randomElement = myStuff[Math.ceil(Math.random() * myStuff.length)];
• randomElement = myStuff[Math.random(myStuff.length)];
• randomElement = Math.random(myStuff.length);

106. How can global variables be declared in JavaScript?

Answers:

• All variables are local in JavaScript.
• Declare the variable between the ‘script’ tags, and outside a function to make the variable global
• Precede the variable name with the constant global
• Declare the variable in an external file

107. Which of the following methods will copy data to the Clipboard?

Answers:

• execClipboard(‘Copy’)
• copyCommand(‘Clipboard’)
• execCommand(‘Copy’)
• execClipboard(‘Copy’)

108. Which of the following code snippets trims whitespace from the beginning and end of the given string str?

Answers:

• str.replace(/^\s+|\s+$/g, »);
• str.replace(/^\s+/,»);
• str.replace(/\s+$/,»);
• str.replace(/\s+/g,’ ‘);

109. Which of the following can be used to invoke an iframe from a parent page?

Answers:

• window.frames
• document.getElementById
• document.getelementsbyname
• document.getelementsbyclassname

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

• It calculates an array’s length.
• It compares ‘a’ and ‘obj’ in an array.
• The code will cause an error.
• It checks if an array contains ‘obj’.

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

• The paragraph.
• The image.
• It depends on other rules.

112. Which of the following code snippets gets an image’s dimensions (height & width) correctly?

Answers:

• var img = document.getElementById(‘imageid’); var width = img.clientWidth; var height = img.clientHeight;
• var img = document.getElementById(‘imageid’); var width = img.width; var height = img.height;
• var img = document.getElementById(‘imageid’); var width = img.getAttribute(‘width’); var height = img.getAttribute(‘height’);
• var img=document.getElementById(«imageid»); var width=img.offsetWidth; var height=img.offsetHeight;

113. Which of the following statements are true regarding the code below?

<script>
alert(«foo» === new String(«foo»)); // output false
</script>

Answers:

• The «===» operator always returns false.
• 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.
• The «===» operator returns true only if the object (comparing by reference) and the primitive have the same value.
• The «===» operator does not work for objects.

114. Which of the following statements are true regarding the «this» keyword in JavaScript?

Answers:

• The value of «this» can be set by assignment during execution, and it will be the same each time the function is called.
• Inside a function, the value of «this» depends on how many times the function is called.
• Inside a function, the value of «this» depends on how the function is called (as a simple call, an object method, a constructor, etc.).
• In strict mode, the value of «this» may change from whatever it is set to, when entering the execution context.

115. Which of the following is not a correct way to empty the array a?

Answers:

• a = new Array();
• a = [];
• a.splice(0,a.length);
• a.clear()

116. Which of the following is the correct way to resize an iframe based on content?

Answers:

• function resizeIframe(height)
{document.getElementById(‘frame_name_here’).height = parseInt(height)+60;}
<iframe id=’frame_name_here’ src=’src.htm’></iframe>
• function resizeIframe(height)
{document.getElementByName(‘frame_name_here’).height = parseInt(height)+60;}
<iframe id=’frame_name_here’ src=’src.htm’></iframe>
• function resizeIframe(height)
{document.getElementByDivId(‘frame_name_here’).height = parseInt(height)+60;}
<iframe id=’frame_name_here’ src=’src.htm’></iframe>
• None of these

117. Consider the three variables:

someText = ‘JavaScript1.2’;
pattern = /(\w+)(\d)\.(\d)/i;
outCome = pattern.exec(someText);

What does pattern.ignoreCase contain?

Answers:

• true
• false
• undefined
• null
• 0

118. Which of the following is not a valid JavaScript function?

Answers:

• apply()
• call()
• toString()
• All the other options are valid.

119. What does the following code snippet do?

<input type=»radio» name=»r1″ value=»radio1″ onclick=»this.checked=false;alert(‘sorry’)»>

Answers:

• The code is invalid.
• The code makes it necessary for the user to select the radio button.
• The code disables the radio button.
• The code displays an alert when the user selects the button.

120. How can properties be added to an object class?

Answers:

• With the prototype() method
• With the prototype property
• It cannot be done.
• With the «this» object

121. Which of the following will correctly check if an object is an array?

Note: There may be more than one right answer.

Answers:

• Object.prototype.toString.call(arr) === ‘[object Array]’
• Array.isArray(arr)
• Object.isArray(arr)
• None of these

122. Which of the following check if an object has a specific property?

Answers:

• hasOwnProperty()
• hasProperty()
• It is browser-dependent.
• None of these.

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

• The second attribute, name, should be the same.
• The name attribute should be null.
• The name attribute should be omitted.
• The name attribute should be different.
• None of these.

124. Which of the following code snippets renders a button invisible?

Answers:

• var button = document.getElementById(‘buttonId’);
button.style.display=’none’
• var button = document.getElementById(‘buttonId’);
button.style.display=’block’
• var button = document.getElementById(‘btn’);
button.style.visibility=’false’;
• var button = document.getElementById(‘btn’);
button.style.visibility=’disabled’;

125. Why does (0 < 5 < 3) return true?

Answers:

• Order of operations produces (true < 3), which returns true.
• Order of precedence produces (true < 3), which returns true.
• Order of operations produces (false < 3), which returns true.
• None of these

126. What is the cleanest, most effective way to validate decimal numbers in JavaScript?

Answers:

• IsNumeric()
• isNaN()
• valid()
• isDecimal()

127. Consider three variables:

someText = ‘JavaScript1.2’;
pattern = /(\w+)(\d)\.(\d)/i;
outCome = pattern.exec(someText);

What does pattern.global contain?

Answers:

• true
• false
• undefined
• null
• 1

128. Which of the following is the best reason for not using «for…in» with array iteration?

Answers:

• for..in should be used to iterate over an array where index order is important.
• for..in should not be used to iterate over an array where index order is important.
• for…in loops iterate over non–enumerable properties.
• for…in loops do not iterate over enumerable properties.

129. What does the + sign in front of a function name mean in JavaScript?

Answers:

• It forces the parser to treat the + sign as a part of an expression.
• The + sign is used as a cast operator.
• It is used to denote a type of object in JavaScript.
• None of these.

130. Which of the following will implement a singleton pattern in JavaScript?

Answers:

• <script>
var anObject = {
method1: function () {
// …
},
method2: function () {
// …
}
};
</script>
• <script>
function method1(){
// …
}
function method2(){
// …
}
</script>
• <script>
var method1 = function(){
// …
}
var method2 = function(){
// …
}
</script>
• <script>
var method1;
var method2;
</script>

131. Which of the following code snippets will correctly detect a touchscreen device?

Answers:

• function isTouchDevice() {
return !!(‘ontouchstart’ in window) || !!(‘onmsgesturechange’ in window);
};
• function isTouchDevice() {
try {
document.body.createEvent(«TouchEvent»);
return true;
} catch (e) {
return false;
}
}
• function isTouchDevice(){
return (typeof(navigator.ontouchstart) != ‘undefined’) ? true : false;
}
• function isTouchDevice(){
return (navigator.msMaxTouchPoints == 0);
}

132. Which of the following shows examples of valid auto increment/decrement loops?

Answers:

• for(var i=0; i < 100; i++){}
for(var i=0; i > -100; i—){}
• for(var i=0; i < 100; i+){}
for(var i=0; i > -100; i-){}
• for(var i=0; i > 100; i++){}
for(var i=0; i < -100; i—){}
• for(var i=0; i > 100; i+){}
for(var i=0; i < -100; i-){}

133. 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
• ain
• 7,29
• 7
• ain,ain

134. 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?

Note: There may be more than one right answer.

Answers:

• obj1.merge(obj2);
• 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;
}
• 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;
}
• Object.extend = function(destination,source) {
for (var property in source)
destination[property] = source[property];
return destination;
}
obj1.extend(obj2)

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

a. document
b. window
c. history
d. browser
e. form
f. location

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

• var timestamp = new Date().getTime();
• var timestamp = Number(new Date());
• var timestamp = Date.now;
• var timestamp = new Date().valueOf();

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

• if(typeof(variable1)==’object’ && typeof(variable2)==’array’){
Object.size(variable1);
variable2.length;
}
• if(typeof(variable1)==’array’ && typeof(variable2)==’object’){
Object.size(variable1);
variable2.length;
}
• if(typeof(variable1) > typeof(variable2)){
Object.size(variable1);
variable2.length;
}
• if(typeof(variable1) == typeof(variable2)){
Object.size(variable1);
variable2.length;
}

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

a.push(b);
a.splice(0,0,b);
a = b.concat(a);
a.join(b);

139. How can it be determined if JavaScript is disabled in the user’s browser?

Answers:

• It is browser-dependent.
• There is no way to detect if JavaScript is disabled.
• Use the HTML <noscript> tag to display different content if JavaScript is disabled.
• None of these.

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

• Jani,Hege,Stale,Kai Jim,Borge
Lene,Jani,Hege,Stale,Kai Jim,Borge
• Jani,Hege,Stale,Kai Jim,Borge
Jani,Hege,Lene,Stale,Kai Jim,Borge
• Jani,Hege,Stale,Kai Jim,Borge
Jani,Hege,Stale,Kai Jim,Lene,Borge
• Jani,Hege,Stale,Kai Jim,Borge
Jani,Hege,Stale,Kai Jim,Borge

141. Consider the following scenario:
The document.write() method is embedded to write some text within a pair of <td></td> 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:

• The browser does not support JavaScript.
• An older version of the browser is being used.
• The browser does not support cookies.

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

• 13
• 20
• 6
• None of these

143. Consider the following code:
var vNew=new Date()
Which of the following options will return true?

Answers:

• vNew instanceof boolean
• vNew instanceof object
• vNew instanceof Date
• All of these

144. Which of the following will detect if the browser supports a certain CSS property?

Answers:

• typeof document.body.style.borderRadius == ‘string’
• typeof document.body.style.borderRadius == ‘undefined’
• typeof document.body.style.borderRadius == true
• It is impossible.

145. Which of the following is not a valid JavaScript operator?

Answers:

• *=
• /=
• %=
• ^+

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:

• window.location.href = «http://stackoverflow.com»;
• window.location.href («http://stackoverflow.com»);
• window.location.replace=»http://stackoverflow.com»;
• 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:

• There is no difference between the two statements.
• The first statement is incorrect and the second one is correct.
• 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?

<button id»newbtn» onclick=»grt();»>Upload</button>
<form>
<input id=»thisId» type=»file» name=»upload» />
</form>
</form>

Answers:

• function grt(){document.getElementById(‘thisId’).keypress();}
• function grt(){document.getElementById(‘thisId’).load();}
• function grt(){document.getElementById(‘thisId’).dblclick();}
• function grt(){document.getElementById(‘thisId’).click();}

149. Choose another way to write x ? a = b : a = c

Answers:

• if (‘x’) { a = b; } else { a = c; }
• if (x) { a = c; } else { a = b; }
• x : a = c ? a =
• None of above

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

• Both codes are equally efficient.
• The first code is more efficient because it contains less code.
• The first code is more efficient because it employs object caching.
• The second code is more efficient because it employs object caching.

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

• var str=»This is test for javascript search !!!»;
if(str.search(«for») != -1) {
alert(«true»);
}
else {
alert(«false»);
}
• var str=»This is test for javascript search !!!»;
if(str.indexof(«for») != -1) {
alert(«true»);
}
else {
alert(«false»);
}
• var str=»This is test for javascript search !!!»;
if(str.indexOf(«for») != -1) {
alert(«true»);
}
else {
alert(«false»);
}
• var str=»This is test for javascript search !!!»;
if(str.contains(«for») != -1) {
alert(«true»);
}
else {
alert(«false»);
}

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

• var div = top.Frame2.document.getElementById(‘some’);
div.style.color= «orange»;
• var div = document.getElementById(‘some’);
div.style.color= «orange»;
• var div = top.Frame1.document.getElementById(‘some’);
div.style.color= «orange»;
• None of these.

153. What value would JavaScript assign to an unitialized variable?

Answers:

• Nan
• null
• undefined
• false

154. Which of the following JavaScript Regular Expression character classes finds any non-digit character in a given string?

Answers:

• \W
• \S
• \B
• \D

155. Which best describes void?

Answers:

• A method
• A function
• A statement
• An operator
• A built-in object

156. Which of the following is used to solve the problem of enumerations in JavaScript?

Answers:

• let
• Regex
• Generators
• E4X

157. Which of the following cannot be achieved using JavaScript?
Note: There may be more than one right answer.

Answers:

• Read or write from external files (except .js files)
• Access or modify browser settings
• Launch client processes (eg windows applications)
• Launching the default email application of the client

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

• for (var key in validation_messages) {
var obj = validation_messages[key];
for (var prop in obj) {
alert(prop + » = » + obj[prop]);
}
}
• Object.keys(validation_messages).forEach(function(key) {
var obj = validation_messages[key];
Object.keys(obj).forEach(function(key) {
alert (prop + “ = “ + obj[key]);
)};
• (validation_messages.hasOwnProperty(key)) {
var obj = validation_messages[key];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
alert(prop + “ = “ + obj[prop]);
}
}
}
}
• _.each(validation_messages, function(value, key){
_.each(value, function(value, key){
alert(prop + » = » + value);
});
});

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

• now
• (now)
• 15
• 19

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

• «*» and «+»
• «/» and «%»
• «/» and «+»
• «*» and «%»

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

• exit
• return
• continue
• while
• break

162. What is the best way to make optional parameters of functions?

Answers:

• function someFunction(requiredArg, optionalArg) {
optionalArg = optionalArg || ‘defaultValue’;
alert(optionalArg);
}
• function someFunction(requiredArg, optionalArg) {
optionalArg = (typeof optionalArg === «undefined») ? «defaultValue» : optionalArg;
alert(optionalArg);
}
• function someFunction(requiredArg, optionalArg) {
optionalArg = (optionalArg === «undefined») ? «defaultValue» : optionalArg;
alert(optionalArg);
}
• All of these

163. Which of the following are correct closure functions?

Answers:

• function foo(x) {
var tmp = 3;
return function (y) {
alert(x + y + (++tmp));
}
}
var bar = foo(2); // bar is now a closure.
bar(10);
• function foo(x) {
var tmp = 3;
function bar(y) {
alert(x + y + (++tmp));
}
bar(10);
}
foo(2)
• function foo(x) {
var tmp = 3;
function bar(y) {
function bar1(tmp) {
alert(x + y + (++tmp));
}
}
bar(10);
}
foo(2)
• 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);

164. Which of the following will correctly detect browser language preference?

Answers:

• var language = window.navigator.userLanguage || window.navigator.language;
alert(language);
• var language = navigator.browserLanguage || window.navigator.language;
alert(language);
• var language =navigator.userLanguage;
alert(language);
• var language = window.navigator.language;
alert(language);

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

• true
true
false
• true
true
true
• true
false
true
false
true
true
• true
true
false
true

166. Which of the following is a good reason why JavaScript variables would start with a dollar sign ($)?

Answers:

• $ is a prefix used to create a instance of a object.
• $ is a keyword in JavaScript.
• $ is used to quickly identify and parse variables
• None of these

167. What is the output of the following code?

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

Answers:

• 700
• 60
• 0
• 760

168. Which of the following code is correct for validating date values?
Note: There may be more than one right answer.

Answers:

• var d = Date.parse(‘foo’);
if (isNaN(d)==false)
{
alert(new Date(d));
} else {
alert(‘Invalid date’);
}
• var d = new Date(‘foo’);
if (d instanceof Date && isFinite(d))
{
alert(d);
} else {
alert(‘Invalid date’);
}
• Date.prototype.valid = function() {
return isFinite(this);
}
var d = new Date(‘foo’);
if (d.valid())
{
alert(d);
} else {
alert(‘Invalid date’);
}
• All of the above

169. Which of the following correctly explains the difference between a «for…in» and a «for» loop?

Answers:

• «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.
• «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.
• «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.
• «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.

170. Which of the following will list the properties of a JavaScript object?

Answers:

• var keys = Object.keys(myJsonObject);
• var keys = Object.value(myJsonObject)
• var keys = Object.keys(myJsonValue)
• None of these

171. What is the difference between setTimeout and setInterval in JavaScript?
Note: There may be more than one right answer.

Answers:

• setInterval executes a function or code snippet a certain amount of time after setInterval() is called, while setTimeout executes a function or code snippet a certain amount of time after the previous timeout fired.
• setTimeout executes a function or code snippet a certain amount of time after setTimeout() is called, while setInterval executes a function or code snippet a certain amount of time after the previous interval fired.
• setTimeout() triggers only once, while setInterval() triggers repeatedly.
• There is no difference between setTimeout() and setInterval().

172. What will be the output of this code?
parseInt(1 / 0, 19);

Answers:

• 1
• 0
• 20
• 18

173. What will the function NaN return for the condition NaN == NaN?

Answers:

• true
• false
• error
• 0

174. What is the output of following charsets in javascript?
++[[]][+[]]+[+[]]

Answers:

• 0
• 10
• 100
• 1000

175. While coding a loop, which statement can be used to ignore the rest of the statements, and continue with the beginning of the loop?

Answers:

• exit
• return
• continue
• while
• break

176. Which of the following code samples prints false?

Answers:

• var n = 3.2;
alert(n===+n && n!==(n|0));
• var n = 3;
alert(n===+n && n===(n|0));
• var boolValue = new Boolean(«false»);
alert(boolValue);
• var n=3.2;
alert(n % 1 === 0);

177. The statement navigator.platform indicates ‘Win16’ on user’s computer that’s running Windows NT. Which of the following is true?

Answers:

• navigator.platform is supposed to show ‘Win16’ on Windows NT.
• The userAgent property reflects the correct operating system.
• The property can be modified.
• navigator.platform shows the operating system for which the browser was compiled for.
• The browser version is outdated.

178. How can GUIDs/UUIDs be created in JavaScript?

Answers:

• GUIDs/UUIDs cannot be created in JavaScript.
• There is no specific method to create GUIDs/UUIDs, but it’s possible to generate GUID-like random numbers in JavaScript.
• JavaScript has methods only for generating GUIDs/UUIDs with only capital letters.
• JavaScript has methods for creating and automatically changing GUIDs/UUIDs.

179. Which of the following is the correct method to use, in order to know the name of both the Object and Object Class in JavaScript?

Answers:

• toSource()
• valueOf()
• toString()
• getName()

180. How does the <this> keyword work within a JavaScript object literal?

Answers:

• <script>
var foo = {};
foo.someMethod = function(){
alert(this);
}
</script>
• <script>
someMethod = function(){
alert(this);
}
</script>
• <script>
var foo = {};
someMethod.foo = function(){
alert(this);
}
</script>
• <script>
var foo = {};
someMethod = function(foo){
alert(this);
}
</script>

181. <a href=’http://w3.org/’ onclick=’someFunc(); return false;’>Click here!</a>

What does «return false» do to this onclick event?

Answers:

• It prevents the default browser behavior from taking place alongside someFunc().
• It prevents someFunc() to run from a second click.
• It prevents someFunc() from returning any values.
• None of the above.

182. Which of the following is the best way of retrieving DOM elements using CSS class names?

Answers:

• var className = ‘someClassName’;
var retrievedElements= [];
var myclass = new RegExp(‘\\b’+className+’\\b’);
var elem = this.getElementsByTagName(‘*’);
for (var i = 0; i < elem.length; i++) {
var classes = elem[i].className;
if (myclass.test(classes)) retrievedElements.push(elem[i]);
}
• var className = ‘someClassName’;
var retrievedElements= document.getElementsByClassName(className);
• var className = ‘someClassName’;
var retrievedElements= [];
var elem = this.getElementsByTagName(‘*’);
for (var i = 0; i < elem.length; i++) {
var classes = elem[i].className;
if (className.indexOf(classes) == 0) retrievedElements.push(elem[i]);
}
• It is not possible to retrieve DOM elements using CSS class names.

183. What is the correct code snippet to change image source?

Answers:

• document.getElementById(«imgageId»).src = «newImage.png»;
• document.getElementById(«imgageId»).longdesc = «newImage.png»;
• document.getElementById(«imgageId»).href = «newImage.png»;
• document.getElementById(«imgageId») = «newImage.png»;

184. When toggling a variable, its cycle must be 0 and 1. When the variable’s active value is 0, the next value should be 1, and when the variable’s active value is 1, the next value should be 0.

Considering the scenario above, which of the following is correct?

Answers:

• q = (q == 1 ? 1 : 0);
• q = 1 — q;
• q ^= 0;
• q = inv(0);

185. Given a TextArea element with ID «text», which will disable the resizable property of the TextArea?

Answers:

• document.getElementById(«text»).style.resize = «none»;
• document.getElementById(«text»).style.resize = «disabled»;
• document.getElementById(«text»).resize = «none»;
• document.getElementById(«text»).resize = «disabled»;

186. Which method evaluates a string of JavaScript code in the context of the specified object?

Answers:

• parseInt
• Eval
• parseFloat
• Efloat

187. Which of the following will include a JavaScript file in another JavaScript file?
Note: There may be more than one right answer.

Answers:

• Adding a script tag with the script URL in the HTML
• Loading it with an AJAX call then using eval
• Using ‘import’ operator
• Using ‘include’ operator

188. Suppose you receive url of mp3 from server to play it right away. How would you implement this code snippet?

Answers:

• var audio = new Audio();
audio.play();
• var audio = new Audio(url);
audio.play();
• var audio = new Audio(url);
audio.load();
• var audio = new Audio();
audio.setAttribute(«href», url);
audio.load();
audio.play();

189. Which of the following is the correct way to stop setInterval() from calling a function in JavaScript?

Answers:

• setInterval() returns an interval ID, which can pass to clearInterval() to stop it from calling its designated function.
• Cannot stop the setInterval() from calling its designated function.
• Stopping setInterval() is browser-dependent; some browsers support stopping setInterval(), others don’t.
• None of these.

190. Which of the following code samples is correct?

Answers:

• var param1 = encodeURIComponent(«http://xyz.com/?a=1&b=2»);
var param2 = encodeURIComponent(«http://abc.com/?a=2&b=5»);
var url = «http://test.odesk.com/file name.html?param1=» + param1 + «&param2=» + param2;
location.href = encodeURI(url);
• var param1 = encodeURIComponent(«http://xyz.com/?a=1&b=2»);
var param2 = encodeURIComponent(«http://abc.com/?a=2&b=5»);
var url = «http://test.odesk.com/file name.html?param1=» + param1 + «&param2=» + param2;
location.href = url;
• var param1 = encodeURI(«http://xyz.com/?a=1&b=2»);
var param2 = encodeURI(«http://abc.com/?a=2&b=5»);
var url = «http://test.odesk.com/file name.html?param1=» + param1 + «&param2=» + param2;
location.href = encodeURIComponent(url);
• var param1 = encodeURIComponent(«http://xyz.com/?a=1&b=2»);
var param2 = encodeURIComponent(«http://abc.com/?a=2&b=5»);
var url = «http://test.odesk.com/file name.html?param1=» + param1 + «&param2=» + param2;
href.location = encodeURI(url);

191. Which of the following statements about the ‘new’ keyword is incorrect?

Answers:

• It creates a new object.
• It sets the constructor property of the object to ‘Object’.
• It prevents any user-defined function from being called as a constructor.
• It executes a constructor function.

192. How can you calculate the number of arguments received by the function?

Answers:

• Using arguments.length
• Using args.length.
• Using count(arguments)
• Can not be determined

193. Which of the following statements are true regarding «window.onload» and «<body onload=»»/>»?

Answers:

• There is no difference between «window.onload» and «<body onload=»»/>», and there is no general preference between the two, as far as best practices is concerned.
• «window.onload» and «<body onload=»»/>» are functionally equivalent, but «<body onload=»»/>» is preferred because it combines the JavaScript code with the HTML markup.
• «window.onload» and «<body onload=»»/>» are functionally equivalent, but «window.onload» is preferred because it separates the JavaScript code from the HTML markup.
• None of the above.

194. The following codes are for comparing equality operators «==» and «===» in JavaScript.
Which of the following are the correct results?
Note: There may be more than one right answer.

Answers:

• var a = «12» + «3»;
var b = «123»;
return (a === b);
result: true
• var a = [1,2,3];
var b = [1,2,3];
return (a == b);
result: false
• var a = { x: 1, y: 2 };
var b = { x: 1, y: 2 };
return (a === b);
result: true
• var a = new String(«123»);
var b = «123»;
return (a === b);
result: true
• var a = { x: 1, y: 2 };
var b = { x: 1, y: 2 };
return (a == b);
result: true

195. Which of the following code prints false?

Answers:

• var boolValue = new Boolean(«false»);
alert(boolValue);
• var boolValue = new Boolean();
alert(boolValue);
• var boolValue = String(«false») == «false»;
alert(boolValue);
• var boolValue = «false»;
alert(!!boolValue);

196. Which of the following statements are correct about null and undefined?

Answers:

• Undefined indicates that a variable has not been assigned a value. Null can be assigned to a variable as a representation of no value.
• Both undefined and null indicate that a variable has not been assigned a value.
• Null is a primitive value used when a variable has not been assigned a value. Undefined is a primitive value that represents an empty or non-existent reference.
• None of these.

197. Which of the following will include a CSS style sheet in page, after an event has occurred?

Answers:

• document.write(<link rel=»stylesheet» type=»text/css» href=»somestyle.css» />);
• document.createStyleSheet(‘somestyle.css’);
• var styles = «@import url(‘somestyle.css ‘);»;
var newSS = document.createElement(‘link’);
newSS.rel = ‘stylesheet’;
newSS.href = ‘data:text/css,’ + escape(styles);
• None of these.

198. Which of the following statements regarding prototypes in JavaScript is not correct?

Answers:

• The prototype property allows you to add properties and methods to an object.
• The prototype property is initially an empty object, and can have members added to it.
• Every object has a prototype by default.
• Prototype does not have a prototype.

199. Which of the following statements is incorrect regarding SVG?

Answers:

• SVG stands for Scalable Vector Graphics.
• SVG graphics do NOT lose any quality if they are zoomed or resized.
• Element and attribute in SVG files cannot be animated
• SVG images can be searched, indexed, scripted, and compressed.
• SVG is a W3C recommendation

200. Suppose you have a circle element of SVG element. How to draw black border with width 10px for this circle element?

Answers:

• circle.setAttribute( “stroke”, “#000000”);
circle.setAttribute( “stroke-width”, “10”);
• circle.setAttribute( “border-color”, “#000000”);
circle.setAttribute( “border-width”, “10”);
• circle.setAttribute( “border”, “#000000; 10”);
• circle.setAttribute( “stroke”, “#000000 10”);

201. What is the correct format for adding comments to a JSON file?

Answers:

• /* comment */
• <!— comment —>
• <? comment ?>
• Comments aren’t allowed inside JSON files.

202. How can you get the type of arguments passed to a function?

Answers:

• using typeof operator
• using getType function
• Both of the above.
• None of the above.

203. Which operator creates a new object from the specified object type?

Answers:

• obj
• create
• new
• None of the above

204. Which of the following variable examples is/are undefined?

Answers:

• var a;
• var a = “undefined”;
• var a = undefined;
• All of the above

205. How many type(s) of storage HTML5 supports?

Answers:

• 1
• 2
• 3
• 4

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

• It’s invalid JSON code.
• It makes it difficult for a third-party to insert the JSON response into an HTML document with a <script> tag.
• It iterates the JSON response.
• It prevents the JSON response from getting executed

207. Which of the following code snippets sets cookie correctly?

Answers:

• document.cookie = «username=John;password=John#1»;
• document.cookie = «username:John;password:John#1»;
• document.cookie(«username=John;password=John#1»);
• document.cookie = «username=John password=John#1»;

208. Which of the following code snippets sets the cookie which will expire when the browser is closed down?

Answers:

• var cookie_date = new Date ( );
cookie_date.setTime ( cookie_date.getTime() — 1 );
document.cookie = «username=John;password=John#1;expires=» + cookie_date.toGMTString();
• document.cookie = «username=John;password=John#1»;
• var cookie_date = new Date ( );
cookie_date.setTime ( cookie_date.getTime() + 1000 );
document.cookie = «username=John;password=John#1;expires=» + cookie_date.toGMTString();
• document.cookie = «username=John;password=John#1;expires=0»;

209. Imagine you have canvas which has image in its content. How to capture HTML Canvas as image?

Answers:

• var canvas = document.getElementById(«canvasID»);
var url = canvas.toDataURL(«image/png»);
document.write(‘<img src=»‘+url+'»/>’);
• var canvas = document.getElementById(«canvasID»);
var context = canvas .getContext(«2d»);
var imgData=ctx.getImageData(10,10,50,50);
document.write(imgData);
• var canvas = document.getElementById(«canvasID»);
var context = canvas .getContext(«2d»);
var img=document.getElementById(«someImageId»);
context.drawImage(img,0,0);
• It is not possible.

210. What kind of Typed Arrays representation of the pixels does Canvas ImageData return when you call ImageData.data?

Answers:

• Uint8ClampedArray
• Uint8Array
• Int8Array
• Uint32Array

211. Which of the following is not a valid variable name?

Answers:

• myvar
• my_var
• 5myvar
• myvar_5

212. Can Javascript functions be nested?

Answers:

• Yes
• No

213. Suppose you have several pages in different locations and need to implement messaging between them. How would you solve security issues?

Answers:

• Not to add any event listeners for message events. This is a completely foolproof way to avoid security problems.
• Always verify the sender’s identity using the origin and possibly source properties, always verify the syntax of the received message.
• use postMessage method in the following form
friendPage.postMessage(«someMessage», *);
• use listener method in the following form
function receiveMessage(event) {
if (event.origin == senderURL) {
return;
}
// do whatever you want
}
window.addEventListener(«message», receiveMessage, false);

214. What is the event that fires when the form element textarea loses the focus?

Answers:

• Onclick
• Ondbclick
• Onfocus
• Onblur

215. Which of the following can be used to handle the user clicking on a node?
Note: There may be more than one right answer.

Answers:

• node.addEventListener( “click”, myFunction, false)
• node.addEventListener( “onclick”, myFunction, false)
• node.onclick = myFunction
• node.attachEvent( “onclick”, myFunction)

216. Which of the following is not a mouse event?

Answers:

• onmousescroller
• onclick
• onmouseover
• onmousemove

217. What is the correct way to create a JavaScript array?

Answers:

• var cars = [“Saab”, “Volvo”, “BMW”];
• var cars = “Saab”, “Volvo”, “BMW”
• var cars = 1 = (“Saab”), 2 = (“Volvo”), 3 = (“BMW”)
• var cars = (1:”Saab”, 2:“Volvo”, 3:“BMW”);

218. What will following code print on browser console?

var foo = function foo() {
console.log(foo === foo);
};
foo();

Answers:

• true
• false
• nothing
• It will raise an exception.

219. What command skips the rest of a case statement?

Answers:

• return
• exit
• continue
• break

220. What method can’t be used with a window object?

Answers:

• open
• read
• write
• close

221. How can you detect the client’s browser name?

Answers:

• client.navName
• browser.appName
• navigator.appName
• None of these

222. Which of the following is/are the correct way to redirect to a URL in javascript?
Note: There may be more than one right answer.

Answers:

• document.href= ‘http://www.foobar.com’;
• window.location.assign (“http://www.foobar.com”)
• window.location = ‘http://www.foobar.com’;
• navigator.location = ‘http://www.foobar.com’;

223. Which of the following way is the best to check browser support for localStorage and sessionStorage?

Answers:

• if(typeof(Storage)!==”undefined”) {
// Yes! localStorage and sessionStorage support:
// Some code…..
}
else {
// Sorry! No web storage support..
}
• if(sessionStorage!==”undefined”) {
// Yes! localStorage and sessionStorage support:
// Some code…..
}
else {
// Sorry! No web storage support..
}
• if(typeof(localStorage)!==null && typeof(sessionStorage)!==null ) {
// Yes! localStorage and sessionStorage support:
// Some code…..
}
else {
// Sorry! No web storage support..
}
• if(localStorage)!==”undefined”) {
// Yes! localStorage and sessionStorage support:
// Some code…..
}
else {
// Sorry! No web storage support..
}

224. For the following html element, which is the correct method to change the font size to 25px using javascript?
< p id = “foo”>Lorem Ipsum</ p >

Answers:

• document.getElementById(“foo”).setFontSize = “25px”;
• document.getElementById(“foo”).style.FontSize = “25px”;
• document.getElementById(“foo”).fontSize = “25px”;
• document.getElementById(“foo”).style(“font-size = 25px”);

225. Which Window method is used to call a function or evaluate an expression at specified intervals?

Answers:

• setInterval()
• repeat()
• setTimeout()

226. What will be the output of following code?

function sum() {
var retval = 0;
for (var i = 0, len = arguments.length; i < len; ++i) {
retval += arguments[i];
}
return retval;
}
console.log(sum(1, 2, 3))

Answers:

• It will print 1 on browser console
• It will print 6 on browser console
• It will throw undefined message error

227. Which of following statements is incorrect regarding localStorage and sessionStorage?

Answers:

• localStorage — stores data with no expiration date
• sessionStorage — stores data for one session
• The data stored with session Storage is deleted when the user closes the browser window.
• The data stored with localStorage will not be deleted when the browser is closed, and will be available the next day, week, or year.
• None of above

228. Which of the following methods is used to get the current location of a user?

Answers:

• getUserPosition()
• getCurrentPosition()
• getPosition()
• None of above

229. Suppose you have a following Worker. How do you stop this Worker from the main page?
var w = new Worker(“”workers.js””);

Answers:

• w.terminate();
• w = null;
• w.close();
• w.postMessage(“stop”);

230. Which of the following statements is incorrect regarding HTML5 Web Worker?

Answers:

• A web worker is a JavaScript that runs in the background.
• It runs independently of other scripts, without affecting the performance of the page
• The data from the web worker is stored in event.source
• postMessage() method — which is used to posts a message back to the HTML page.

231. Which of the following statements is incorrect regarding HTML5 Geolocation?

Answers:

• The HTML5 Geolocation is used to get the geographical position of a user and much more accurate for devices with GPS.
• watchPosition() method of Geolocation object — returns the current position of the user and continues to return updated position as the user moves
• The getCurrentPosition() method returns an object if it is successful.
• The position is always available without the user permission.

232. What is the output of the following code?

if (typeof(Storage)!==”undefined”) {
localStorage.age=5;
sessionStorage.age=5;
alert(localStorage.age + sessionStorage.age);
}
else {
alert(“Sorry, your browser does not support web storage…”);
}

Answers:

• 55
• 10
• Sorry, your browser does not support web storage…
• 5undefined

233. What is the output of the following code?

var foo = 123e5;
var bar = 10;
var foobar = foo + bar;
alert(foobar)

Answers:

• 12300010
• 1230000010
• 123e510
• 133

234. What will be the final output ?

var x=3;
x=x<<3;

Answers:

• 1
• 3
• 24
• 9

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

• arr.push(«New Item»)
• arr[arr.length] = «New Item»
• arr.unshift(«New Item»)
• arr.append(«New Item»)

236. What will be the output of following code snippet?

var result = (function(a) {
return a*a;
}(5.5));
alert(result);

Answers:

• 5
• 25
• 10
• 30.25

237. What is the correct JavaScript syntax to change the content of next HTML element?
<p id=»sample»>This is a sample text.</p>

Answers:

• document.getElement(«p»).innerHTML = «Hello World!»;
• #sample.innerHTML = «Hello World!»;
• document.getElementById(«sample»).innerHTML = «Hello World!»;
• document.getElementByName(«p»).innerHTML = «Hello World!»;

238. What is the correct syntax for referring to an external script called «test.js»?

Answers:

• <script name=»test.js»>
• <script href=»test.js»>
• <script src=»test.js»>
• None of these

239. Which of the following code snippets deletes cookie correctly?

Answers:

• var mydate = new Date();
mydate.setTime(mydate.getTime() — 1);
document.cookie = «username=; expires=» + mydate.toGMTString();
• document.cookie = null;
• document.cookie = «username=John;password=John#1»;
• var mydate = new Date();
mydate.setTime(mydate.getTime() + 1000000);
document.cookie = «username=; expires=» + mydate .toGMTString();

240. What will the output of the below code?

function clickValue(){
alert(Math.round(-20.5));
}
clickValue();

Answers:

• -20
• -21
• 20
• 19.5

241. What is not true about anonymous functions?

Answers:

• anonymous functions are created at runtime.
• anonymous functions don’t have a name.
• anonymous functions can not return any value.
• All variables and functions defined within the anonymous function aren’t available to the code outside of it.

242. What will be the output of following code?

var x = 1;
{
var x = 2;
}
alert(x);

Answers:

• 1
• 2
• undefined
• code will raise an exception

243. new String(«This is a JavaScript string») instanceof String evaluates to?

Answers:

• False
• True
• Error
• String

244. Which of the following is the correct method to update the content of an HTML element ‘p’ with id = ‘foo’?

Answers:

• document.getElementById(«foo»).innerHTML = «some text»;
• document.getElementById(«foo»).HTML = «some text»;
• document.getElementById(«foo»).text = «some text»;
• document.getElement(«foo»).innerHTML = «some text»;

245. What will be the output of following code snippet?

var foo = 10;
bar = 3;
(function() {
var foo = 2;
bar= 1;
}())
bar = bar + foo;
alert(bar);

Answers:

• 11
• 3
• 30
• 12

246. Which of the following is incorrect way of instantiating a date?

Answers:

• new Date(dateString)
• new Date()
• new Date(seconds)
• new Date(year, month, day, hours, minutes, seconds, milliseconds)

247. What will be the output of following code?

var x = [typeof x, typeof y][1];
console.log(typeof typeof x);

Answers:

• string
• object
• array
• It will raise an exception

248. What will this code output?

console.log(typeof a);
console.log(typeof b);
function a() {
}
var b = function () {
};

Answers:

• function, function
• function, undefined
• undefined, undefined
• undefined, function
• An error

249. Which of the following is a client side object?

Answers:

• Database
• FileUpLoad
• Client
• Cursor

250. How do you locate the first X in a string variable named txt?

Answers:

• txt.find(‘X’);
• txt.locate(‘X’);
• txt.indexOf(‘X’);
• txt.countTo(‘X’);

251. Which of the following is not a valid function call?

Answers:

• var x = myfunc();
• myfunc;
• x = myfunc();
• myfunc();

252. How to write an IF statement for executing some code if var «my_id» is NOT equal to 10?

Answers:

• if (my_id<>10)
• if my_id =! 10 then
• if my_id <>10
• if (my_id != 10)

253. Evaluate the following expression: ~-(2 + «2»)

Answers:

• undefined
• SyntaxError
• 21
• -22

254. What would be the output of below regular expression code:
/e/.exec(«The best things in life are free!»);

Answers:

• e
• 6
• 4
• true

255. What is the actual way to remove a property from an object?

Answers:

• by setting property to undefined
• by deleting the property using delete operator
• by setting property to null
• You can not delete an individual property from an object.

256. What is the use of «this» keyword in JavaScript?

Answers:

• It refers to current object
• It refers to previous object
• It is variable which contains value
• None of the above

257. Which of the following determines the type of a given object?

Answers:

• variable
• typeof
• string
• object

258. Which of the following is not a valid JavaScript Assignment Operator?

Answers:

• /=
• *=
• =
%=
• ^

259. What is the correct JavaScript syntax to change the content of the HTML element with id «header»?

Answers:

• document.getElementById(«header»).innerHTML = «Updated Header!»;
• #header.innerHTML = «Updated Header!»;
• $header.innerHTML = «Updated Header!»;
• document.getElement(«p»).innerHTML = «Updated Header!»;

260. What will be the output of the following code?
var foo = 10 << 1;

Answers:

• 10
• 20
• 0
• 30
• parse()
• setDay()
• setTime()
• valueOf()

Comments

Popular posts from this blog

English Spelling Test (U.S. Version) Upwork Answers Test 2019

1 . Complete the following sentence by choosing the correct spelling of the missing word. Their relationship was plagued by _______ problems. Perpetual   —- it means: continuing for ever in the same way, often repeated Perpechual Purpetual Perptual 2.  Complete the following sentence by choosing the correct spelling of the missing word. The crowd _________ me on my acceptance into Mensa Congradulated Congrachulated Congratulated  —- it mean: to praise someone Congratilated English Spelling Test (U.S. Version) Answer;Upwork English test answer; Upwork English test answer 2017; lastest Upwork English test answer; upwork test answer;  3. Choose the correct spelling of the word from the options below. Goverment Governmant Government  — the group of people who officially control a country Govermant 4. Choose the correct spelling of the word from the options below. Temperamental  — (of a person) liable to unreasonable changes of mood Tempermental T

Office Skills Test Upwork Test Answers 2019

Question:* Your computer is not printing and a technician is not available, so you perform the following activities to investigate the problem. In which order should you take these up? 1 See if the printer cartridge is finished 2 See if the printer is switched on 3 Try to print a test page using the printer self-test 4 Try to print a test page from Windows 5 See if the printer is properly attached to the computer Answer: • 2,3,1,5,4 Question:* What is 'flexi-time'? Answer: • The flexible use of personal office hours, such as working an hour earlier one day, in order to leave an hour earlier another day. Question:* Which of the following are proven methods of improving your office skills? Answer: • All of the above Question:* When replying to an e-mail, who do you place in the cc: line and who in the bcc: line? Answer: • A person you wish to openly inform goes in the cc: line, and the person you wish to read the e-mail without the knowledge of the rec

Computer Aptitude Test Answers Upwork 2019

1. HGFE is related to ZYXW in the same way as PONM is related to: Answers:   • JKEF • TSRQ • QTSR • EDOQ 2. Refer to the diagram. From the 4 given options, choose the one that completes the series. Answers:   • 1 • 2 • 3 • 4 3. Ronald is taller than George, who is shorter than Bill. George is taller than Jimmy and Hillary, where Hillary is the shortest. Who is the tallest among all? Answers:   • Ronald • Bill • George • Jimmy • Cannot be determined 4. If 123 means "Very hot day", 356 means "hot filtered coffee" and 289 means "day and night", the numeral that stands for "very" is: Answers:   • 5 • 2 • 1 • 9 5. Bodyguard is related to person in the same way as: Answers:   • Teacher : School • Mayor : City • Soldier : Country • Monk : Temple 6. A solid cube is painted green on two adjacent sides and black on the sides opposite to the green sides and yellow on the remaining