IST 226 Final Exam (most questions included)
What is returned when the following code executes?var number = 10;var highest = 18;return ( number > highest ) ? highest : number;
10
What is the value of selected when the following code executes?var num = "3.5";var selected = num && parseFloat(num) || num || "";
3.5
What is the value of selected when the following code executes?var num = undefined;var selected = num && parseFloat(num) || num || "";
""
What is the value of salesTax after the following code executes?var salesTax = 53.937;salesTax = parseFloat( salesTax.toFixed(2) );
53.94
Which of the following operators does NOT perform type coercion?
===
What is displayed in the alert dialog box after the following code is executed? var scores = [70, 20, 35, 15]; scores[scores.length] = 40; alert("The scores array: " + scores); A) The scores array: 70,20,35,15,40 B) The scores array: 40 C) The scores array: 70 20 35 40 D) The scores array:
A) The scores array: 70,20,35,15,40
To execute code after a jQuery effect has finished, you can use A) a callback function B) a global function C) a local function D) a parameterless function
A) a callback function
What will be displayed in the user's browser after the following code executes if the user enters 87 at the prompt? "use strict" var getInfo = function() { grade = parseInt(prompt("What's your score on the test?")); var newGrade = getResult(grade); alert("Your grade, curved, is " + newGrade); }; var getResult = function(grade) { var newGrade = grade + 5; return (newGrade); }; A) an alert will display: Your grade, curved, is 92 B) an alert will display: Your grade, curved, is NaN C) nothing will display; grade is an undeclared variable D) nothing will display; newGrade cannot be declared twice
A) an alert will display: Your grade, curved, is 92
The condition for a while loop is tested A) before the statements in the loop are executed B) after the statements in the loop are executed C) before and after the statements in the loop are executed D) before or after the statements in the loop are executed, depending on how the condition is coded
A) before the statements in the loop are executed
Which of the following types of errors will cause an application to stop executing? A) runtime error B) logic error C) syntax error D) JavaScript engine error
A) runtime error
The img elements for the thumbnails in the code that follows are coded within the <a> elements <main> <h1>Image Swap</h1> <p>Click on an image to enlarge.</p> <ul id="image_list"> <li><a href="images/pic1.jpg" title="dogs"> <img src="thumbnails/t1.jpg" alt=""></a></li> <li><a href="images/pic2.jpg" title="cats"> <img src="thumbnails/t2.jpg" alt=""></a></li> </ul> <h2 id="caption">Animals</h2> <p><img id="main_image" src="images/pic1.jpg" alt=""></p> </main> A) so the user can swap the main image by pressing Enter when a thumbnail has the focus B) so the user can access the thumbnail links by pressing the Tab key C) so the application is easy to use by the motor-impaired D) all of the above
A) so the user can swap the main image by pressing Enter when a thumbnail has the focus
What value is returned by the following expression? !isNaN("12.345") A) true B) false C) NaN D) undefined
A) true
The nodes in the Document Object Model represent:
All of the HTML elements, attributes, content, and comments of a web page.
The opening tag in a form element should include:
An action attribute that specifies the file on the web server that will process the data that is submitted, a method attribute that specifies the HTTP method to be used for sending the form to the web server, and a name attribute if the form will be referred to by client-side or server-side code.
What is the value of random after the following code executes?var random = Math.floor(Math.random() * 10);random = random + 1;
An integer between 1 and 10
Sometimes, validating the HTML code for a web page will help you debug an application, because
a trivial HTML error can cause other types of errors
What is the value of scores[3] after the following code is executed? var scores = [70, 20, 35, 15]; scores[3] = scores[0] + scores[2]; A) 15 B) 105 C) 2 D) 120
B) 105
How many times will the while loop that follows be executed? var months = 5; var i = 1; while (i < months) { futureValue = futureValue * (1 + monthlyInterestRate); i = i+1; } A) 0 B) 4 C) 5 D) 6
B) 4
he code that follows has a bug in it because the second use of the variable named salesTax is spelled with all lowercase letters (salestax). var calculateTax = function(subtotal,taxRate) { var salesTax = subtotal * taxRate; salestax = parseFloat(salesTax.toFixed(2)); return salesTax; }; Assuming that there are no other problems and that you're using strict mode, what will happen when this code is executed? A) The salesTax variable will contain the right value, but it won't be rounded. B) An error will occur because salestax hasn't been declared. C) The salestax variable will contain the rounded sales tax value. D) The salesTax variable will contain null when it is returned.
B) An error will occur because salestax hasn't been declared.
Which of the following is NOT true about using Chrome's developer tools to test an application? A) You can display the developer's tools by pressing F12. B) The Sources panel will display a list of all runtime errors in the order they appear in your code. C) You can set breakpoints to examine the contents of variables at selected points in your code. D) The Watch section of the right pane allows you to enter a variable name or an expression that you want to watch.
B) The Sources panel will display a list of all runtime errors in the order they appear in your code.
The type of loop that provides for varying the value of an index (or counter) is a A) while loop B) for loop C) do-while loop D) all of the above
B) for loop
Which statements are equivalent to the if statements that follow? if (pay >= 500) { tax_rate = 0.3; } if (pay >= 300 && pay < 500) { tax_rate = 0.2; } if ((pay >= 100) && (pay < 300)) { tax_rate = 0.1; } A) if (pay > 100) { tax_rate = 0.1; } else if (pay > 300) { tax_rate = 0.2; } else if (pay > 500) { tax_rate = 0.3; } B) if (pay >= 500) { tax_rate = 0.3; } else if (pay >= 300) { tax_rate = 0.2; } else if (pay >= 100) { tax_rate = 0.1; } C) if (pay >= 500) { tax_rate = 0.3; } else { tax_rate = 0.2; } if (pay > 100) { tax_rate = 0.1; } D) none of the above are equivalent
B) if (pay >= 500) { tax_rate = 0.3; } else if (pay >= 300) { tax_rate = 0.2; } else if (pay >= 100) { tax_rate = 0.1; }
When creating a timer, the delay or interval is specified A) in seconds B) in milliseconds C) in thousandths D) in tenths of a second
B) in milliseconds
Which of the following will test whether a Boolean variable named isValid is true? A) isValid == true B) isValid C) !isValid == false D) all of the above
D) all of the above
Which of the following will test whether a Boolean variable named isValid is true? A) isValid == true B) isValid C) !isValid == false D) all of the above
D) all of the above
Code Example 5-2 var getAvg = function () { var count = 1; var itemTotal = 0; var item = 0; while (count < 4) { item = parseInt(prompt("Enter item cost: ")); itemTotal += item; count++; } var averageCost = parseInt(itemTotal/count); alert("Total cost: $" + itemTotal + ", Average cost: $" + averageCost); }; (Refer to Code Example 5-2) Suppose you tested the getAvg function by entering the values 5, 10, and 15 when prompted and the alert() method displayed "Total cost: $30, Average cost: $7". What type of error is this? A) runtime error B) logic error C) syntax error D) JavaScript engine error
B) logic error
When you test an application with Chrome's developer tools and a breakpoint is reached, you can click A) the Continue button to continue stepping through the statements B) the Step Into button to execute the current statement and move to the next statement C) the Step Over button to skip execution of the next statement D) the Step Out button to continue normal execution of the application
B) the Step Into button to execute the current statement and move to the next statement
What does the evt variable refer to in this code? $("#faqs h2").click(function(evt) { evt.preventDefault(); }; A) the jQuery object B) the event object C) the this keyword D) the selector
B) the event object
If you use a short-circuit operator to combine two expressions A) both expressions are always evaluated B) the second expression is evaluated only if it can affect the result C) the first expression is evaluated only if it can affect the result D) the result of each expression is reversed
B) the second expression is evaluated only if it can affect the result
Which type of object is passed to a function by value?
Boolean
What is the value of the average variable after the following code is executed? var sum = 0; var prices = [14, 10, 9, 12, 11, 14, 10, 8]; for( var i = 0; i < prices.length; i++ ) { sum = sum + prices[i]; } var average = sum/prices.length; A) 7.27 B) 6.72 C) 8 D) 11
C) 8
Assume that the variables named entry and number have starting values of 9 and 3 respectively. What is the value of entry after the following statements are executed? if ((entry > 9) || (entry/number == 3)) { entry--; } else if (entry == 9) { entry++; } else { entry = 3; } A) 3 B) 8 C) 9 D) 10
C) 9
Which HTML element does NOT have a default action associated with the click event? A) <input> B) <button> C) <img> D) <a>
C) <img>
Code Example 7-3 The JavaScript:: 1. var $ = function(id) { 2. return document.getElementById(id); 3. }; 4. var timer; 5. var counter = 10; 6. var updateCounter = function() { 7. counter--; 8. $("counter").firstChild.nodeValue = counter; 9. if (counter <= 0) { 10. clearInterval(timer); 11. document.getElementById("counter").innerHTML = "Blastoff!"; 12. } 13. }; 14. window.onload = function() { 15. timer = setInterval ( updateCounter, 1000 ); 16. }; The HTML: <h3>Countdown: <span id="counter"> 10 </span> </h2> (Refer to Code Example 7-3) Which of the following statements about this code is true? A) It creates a timer that displays a counter on the page that replaces the text "Countdown". B) It creates a timer that uses the setInterval() method to change the updateCounter value every 1000 milliseconds . C) It creates a timer that counts down from 10 to 1 and displays "Blastoff!" in the span element when the counter variable reaches 0. D) It will fail because a timer cannot count down.
C) It creates a timer that counts down from 10 to 1 and displays "Blastoff!" in the span element when the counter variable reaches 0.
If you want the block of code in a loop to be executed at least once, you would normally use A) a while loop B) a for loop C) a do-while loop D) either A or C
C) a do-while loop
A coding error that produces the wrong results when the application is run is known as a A) runtime error B) user error C) logic error D) syntax error
C) logic error
Which of the following code statements gets the value of a text box? A) text() B) text(value) C) val() D) val(value)
C) val()
What does the following code do?var displayError = function ( message ) {alert("Error: " + message);}
Creates a function and stores it in a variable named displayError.
Which of the following is NOT a relational operator? A) > B) >= C) != D) =
D) =
When does the ready() event handler run? A) As soon as the browser starts. B) As soon as the JavaScript load event is done. C) As soon as all the page elements are loaded in the browser. D) As soon as the Document Object Model is built.
D) As soon as the Document Object Model is built
What is displayed in the alert dialog box after the following code is executed? var items = 3; for (var i = 1; i <= items; i++) { var result = 1; for (var j = i; j >= 1; j--) { result *= j; } alert("The factorial of " + i + " = " + result); } A) The factorial of 1 = 1 B) The factorial of 2 = 4 C) The factorial of 3 = 6 D) The factorial of 4 = 24
D) The factorial of 4 = 24
When you use the relational operators, you can compare A) a variable with a literal value B) a variable with another variable C) a variable with an arithmetic expression D) all of the above E) A and B only
D) all of the above
Code Example 7-3 The JavaScript:: 1. var $ = function(id) { 2. return document.getElementById(id); 3. }; 4. var timer; 5. var counter = 10; 6. var updateCounter = function() { 7. counter--; 8. $("counter").firstChild.nodeValue = counter; 9. if (counter <= 0) { 10. clearInterval(timer); 11. document.getElementById("counter").innerHTML = "Blastoff!"; 12. } 13. }; 14. window.onload = function() { 15. timer = setInterval ( updateCounter, 1000 ); 16. }; The HTML: <h3>Countdown: <span id="counter"> 10 </span> </h2> (Refer to Code Example 7-3) The timer in this code will update the counter A) every 10 seconds B) once, after a delay of 1000 milliseconds C) immediately, when the page loads D) every second for 10 times
D) every second for 10 times
Which of the following statements runs a function named newTimer every 3 seconds? A) setTimeout(newTimer, 3); B) setTimeout(newTimer, 3000); C) setInterval(newTimer, 3); D) setInterval(newTimer, 3000);
D) setInterval(newTimer, 3000);
You need to provide cross-browser compatible code to cancel the default action of an event A) so the event can be handled with a single event handler B) to ensure that all browsers store the event object in the global window.event property C) because older IE browsers weren't completely DOM-compliant D) to ensure that all browsers use the preventDefault() method
D) to ensure that all browsers use the preventDefault() method
To view the changes that have been made to the DOM for a page by JavaScript, you can:
Display the HTML for the page in Chrome's Elements panel.
Which of the following statements about check boxes is true?
Each check box must have a unique id attribute.
If a case label of a switch statement doesn't contain a break statement, what will the code execution do?
Fall through to the next label
What is displayed when the following code executes?var statusCode = "403";switch ( statusCode ) {case "200":alert("OK");break;case "403":alert("Forbidden");break;case "404":alert("Not Found");break;default:alert("Unknown Status");break;}
Forbidden
Given HTML that includes the element <p id="ship">shipping cost goes here</p>, what will the following code do if the user enters 100 at the prompt? var getInfo = function() { var cost = parseFloat(prompt("How much does the item cost?")); var ship = cost * .06; document.getElementById("ship").innerHTML = "Shipping: $" + ship.toFixed(2); };
It will replace the text in the <p> element with "Shipping: $6.00".
What is the value of the message variable after the following code executes?var message = "";for (var i = 0; i < 5; i++ ) {message += "L:" + i + ",";}
L:0,L:1,L:2,L:3,L:4,
Which of the following statements about JavaScript libraries is true?
Libraries let you group similar functionality in a single file.
If a numerical operation returns a number greater than the largest possible JavaScript value, it returns
Infinity
What text does the following code display in the dialog box?var investment = "$100";if (isNaN(investment) || investment <= 0) {alert("Investment is not valid.");} else {alert("Investment: " + investment.toFixed(2))}
Investment is not valid.
What does the following code do, assuming that the element with the id "image_list" contains a list of images and that the current value of the class attribute that element is "show"? var list = document.getElementById("image_list"); list.setAttribute("class", "large");
It replaces the current value of the class attribute for the element with the id of "image_list" with the value "large".
What does the following line of code do? $("user").innerHTML = "Hello, good friend!";
It sets the content of the element with "user" as its id attribute to "Hello, good friend!"
When a function's this keyword is undefined, how was the function invoked?
Normally in strict mode
What is displayed when the following code executes?var rate = 0.1;if ( isNaN(rate) ) {alert("Rate is not a number.");} else if (rate < 0) {alert("Rate cannot be less than zero.");} else if (rate > 0.2) {alert("Rate cannot be greater than 20%.");} else {alert("Rate is valid.");}
Rate is valid.
Which of these statements is true?
The call method passes its parameters as a comma-separated list, while the apply method passes them as an array.
Which property would you use to get the node that contains the content for an element?
nodeValue
What text does the following code display in a dialog box?alert("The file is in \"C:\\My Documents\"");
The file is in "C:\My Documents"
Code example 10-3 var tasks = [];var displayTaskList = function() {// get tasks from storageif (tasks.length === 0) {tasks = getStorage("tasks_10");}// display sorted tasks with delete linksdisplaySortedTaskList(tasks, $("tasks"), deleteFromTaskList);// set focus on task text box$("task").focus();}; (Refer to code example 10-3.) Which of the following statements can you be sure is true?
The first argument of the displaySortedTaskList function is an array that's retrieved by the getStorage function.
Code example 10-2 var add = function (val1, val2, val3) {if ( arguments.length < 1 ) return 0;var sum = 0;for ( var i = 0; i < arguments.length; i++) {sum += arguments[i];}return sum;} (Refer to code example 10-2.) If the function is called with this statement var sum = add(1); what happens?
The function returns 1.
Code example 10-2 var add = function (val1, val2, val3) {if ( arguments.length < 1 ) return 0;var sum = 0;for ( var i = 0; i < arguments.length; i++) {sum += arguments[i];}return sum;} (Refer to code example 10-2.) If the function is called with this statement alert (add(1,2,3,4,5)); what happens?
The function returns 15.
Why would the following code for a button not send the form data to the server? <input type="button" value="Register" id="register">
The value of the type attribute should be "submit".
Which of the following statements is NOT true?
To display changes made to the DOM, you must refresh the web page.
What is displayed when the following code executes?var age = 19, score = 750;if ( age >= 21 && score >= 700 ) {alert ("Loan approved");} else if ( age >= 21 && score >= 650 ) {alert ("Cosigner needed.");} else if ( age >= 18 && score >= 680 ) {alert ("Two cosigners needed.");} else {alert ("Loan denied.");}
Two cosigners needed.
Which of the following is NOT one of the three testing phases of a JavaScript application?
Using the developer tools to check the DOM
When you test an application with Chrome's developer tools and a breakpoint is reached, you can view the current data by a) moving the mouse pointer over the name of a variable in the Sources panel b) clicking in the bar to the left of a statement that uses an arithmetic expression c) hovering the mouse pointer over a variable name in the Elements panel d) looking up the variable in the names table in the Console panel
a) moving the mouse pointer over the name of a variable in the Sources panel
For a Textarea object, what property do you use to get the text that has been entered into the text area? a. the value property b. the string property c. the name property d. the text property
a. the value property
Code example 10-1 var add = function( x, y ) {return ( x + y );}alert( add (5, 3) ); (Refer to code example 10-1.) The function
accepts 2 parameters and returns 1 value.
The code that follows has a bug in it because the second use of the variable named salesTax is spelled with all lowercase letters (salestax).var calculateTax = function(subtotal,taxRate) {var salesTax = subtotal * taxRate;salestax = parseFloat(salesTax.toFixed(2));return salesTax;}Assuming that there are no other problems and that you're using strict mode, what will happen when this code is executed?
an error will occur because salestax hasn't been declared
All parameters passed to a function are available in what property of the function?
arguments
For the following code, an event handler named investment_change isvar investment_change = function() {var years = parseInt( $("years").value );alert("Years: " + years);}window.onload = function() {$("investment").onchange = investment_change;}
attached to the onchange event of a control with an id of "investment".
Assuming you have a radio button with an id of "contact_via", which of the following statements selects that radio button? a) $("contact_via").selected = true; b) $("contact_via").checked = true; c) $("contact_via").value = true; d) $("contact_via").enabled = true;
b) $("contact_via").checked = true;
How can you clear a check from a Checkbox object? a. set its clear property to true b. set its checked property to false c. set its value property to an empty string d. call its blur method
b) set its checked property to false
What method would you use to remove the focus from a control?
blur()
Because JavaScript uses lexical scope, you can tell the scope of a variable
by where it is located in the JavaScript code
What does the code that follows do?$("email").firstChild.nodeValue = "Entry is invalid."; a) Sets the text for the first child of the element with "email" as its id attribute. b) Gets the text for the element with "email" as its id attribute. c) Sets the text for the element with "email" as its id attribute. d) Sets the text for the next child of the element with "email" as its id attribute.
c) Sets the text for the element with "email" as its id attribute.
What event occurs when the user selects a new item from a select list? a) the click event b) the dblclick event c) the change event d) the select event
c) the change event
To view the changes that have been made to the DOM for a page by the JavaScript, you can
display the HTML for the page in Chrome's Elements panel
Given a Date object named due_date, which of the following statements sets the month to February?
due_date.setMonth(1);
Which of these for statements displays even numbers from 0 to 10?
for ( var i = 0; i <= 10; i += 2 ) { alert( i ); }
Which method of the Element interface returns true if the element has the specified attribute?
hasAttribute()
How would you rewrite the statement that follows that uses the DOM Core specification to use the DOM HTML specification? imageElement.getAttribute(src);
imageElement.src;
Code example 10-3 var tasks = [];var displayTaskList = function() {// get tasks from storageif (tasks.length === 0) {tasks = getStorage("tasks_10");}// display sorted tasks with delete linksdisplaySortedTaskList(tasks, $("tasks"), deleteFromTaskList);// set focus on task text box$("task").focus();}; (Refer to code example 10-3.) This code is from the main JavaScript file for an application. It calls the getStorage function from a storage library and it calls the displaySortedTaskList function from a task list library. As a result, the script elements for the JavaScript libraries must be in this sequence:
it depends upon whether one library calls functions in the other library
A coding error that produces the wrong results when the application is run is known as a
logic error
Which property of a text node would you use to set the value of that node?
nodeValue
What can you use to clarify the order of relational and logical operations in a conditional expression?
parentheses
Which of the following statements performs a case-insensitive comparison of the strings named text1 and text2?
text1.toLowerCase() == text2.toLowerCase()
What method of the Math object can be used to return the largest value from the values that are passed to it?
the Math.max method
To remove the focus from a control, what method do you use? a. value() b. focus() c. remove() d. blur()
the blur method d. blur()
What property of the Radio object is used to determine if a radio button is selected?
the checked property
What method of the Date object gets the day of the month in local time?
the getDate method
What method of the String object searches the string for an occurence of the specified search string?
the indexOf method
To display data in a span element, you can use the firstChild property to get a pointer to the Text node. Then, what property of the Text node can you use to set the value that's displayed in the span element?
the nodeValue property
When a function is called as an event handler, its this keyword refers to
the object that raised the event
What method of the Number object returns a string with the number rounded to the specified number of decimal places?
the toFixed method
Which parameters are required when you call the Date constructor with number parameters?
the year and month
Which of the following statements is NOT a valid way to create a date object named birthday?
var birthday = "12/2/1978";