CPT 226 Final
What is the value of selected when the following code executes?var num = undefined;var selected = num && parseFloat(num) || num || "";
""
What is returned when the following code executes?var number = 10;var highest = 18;return ( number > highest ) ? highest : number;
10
What will the value of the totalsString variable be after the following code is executed?var totals = [141.95, 212.95, 411, 10.95];totals[2] = 312.95;var totalsString = "";for (var i in totals) {totalsString += totals[i] + "|";}
141.95|212.95|312.95|10.95|
Assume userName equals "Tom" and userAge equals 22. What is displayed in a dialog box when the following statement is executed?alert(userAge + " \nis " + userName + "'s age.");
22 is Tom's age.
If you want to store a true or false value in a variable, you use the __________________ data type.
Boolean
Which native object type can you NOT create by assigning a literal value to a variable?
Date
Which of the following isn't a best practice when coding callback functions?
Throw an error if no callback function is sent.
Which of the following statements about an array of arrays is true?
Two indexes are used to access a value that's stored in an array of arrays.
The easiest way to run a web page that's already in your browser after you've made changes to the code for the page is to
click on the Reload or Refresh button
A coding error that produces the wrong results when the application is run is known as a
logic error
Which HTML element typically contains the main content of a web page?
main
In the code that follows, getElementById is a/andocument.getElementById("emailAddress");
method
Which method removes the last element from the end of an array?
pop()
A cascading method is one that
returns the object referred to by the this keyword
What property of the Radio object is used to determine if a radio button is selected?
the checked property
Which parameters are required when you call the Date constructor with number parameters?
the year and month
In a web browser, the ____________________ object is the object that's always available to JavaScript so you don't have to code its name when you call one of its methods.
window
The index value of the first element in a JavaScript array is
zero
Assuming you have a radio button with an id of "contact_via", which of the following statements selects that radio button?
$("contact_via").checked = true;
Code Example 4-3var tax = .07;var getCost = function(itemCost, numItems) {var subtotal = itemCost * numItems;var tax = 0.06;var total = subtotal + subtotal * tax;return (total);}var totalCost = getCost(25.00, 3);alert("Your cost is $" + totalCost.toFixed(2) + " including a tax of " +tax.toFixed(2)); (Refer to Code Example 4-3) What is the value of the global variable, tax?
.07
If totalMonths has a string value of "13", what does the code that follows display? var years = parseInt ( totalMonths / 12 );var months = totalMonths % 12;if ( years == 0 ) {alert ( months + " months.");} else if ( months == 0 ) {alert ( years + " years");} else {alert ( years + " years, and " + months + " months.");}
1 years, and 1 months
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];
105
What will futureValue contain after the for loop has been executed one time?var years = 10;var annualRate = 10;var futureValue = 1000;annualRate = annualRate / 100;for ( i = 1; i <= years; i++ ) {futureValue += futureValue * annualRate;}
1100
What is the value of the totalsString variable after the following code is executed?var totals = [141.95, 212.95, 411, 10.95];totals[2] = 312.95;var totalsString = "";for (var i = 0; i < totals.length; i++) {totalsString += totals[i] + "|";}
141.95|212.95|312.95|10.95|
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 the variable named counter after the code that follows is executed? var percent = 0.54;var isValid = true;var counter = 1;if ((percent > 0.50) && (isValid == true)) {counter += 2;if (isValid == true) {counter++;} else if (percent >= 0.50) {counter += 3;}}else {counter++;}
4
Code example 16-1var testScores = [];testScores[0] = [80, 82, 90, 87, 85];testScores[1] = [79, 80, 74, 82, 81];testScores[2] = [93, 95, 89, 100, 85];testScores[3] = [60, 72, 65, 71, 79]; (Refer to code example 16-1) This code creates a tabular structure that has
4 rows and 5 columns
After the code that follows is executed, what is the value of discountAmount?var discountAmount;var orderTotal = 200;if (orderTotal > 200) {discountAmount = orderTotal * .3;} else if (orderTotal > 100) {discountAmount = orderTotal * .2;} else {discountAmount = orderTotal * .1;}
40.0
After the code that follows is executed, the variable named userEntry will contain var userEntry = 461.95;userEntry = parseInt(userEntry);
461.95
What is the value of salesTax after the following code executes?var salesTax = 53.937;salesTax = parseFloat( salesTax.toFixed(2) );
53.94
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;}
8
Which of the following is NOT a relational operator?
=
Which of the following operators does NOT perform type coercion?
===
Which of the following statements about for and for-in loops is true?
A for loop processes undefined elements, but a for-in loop skips over them.
How could the following code be improved?var calculateSalesTax = function(amount, taxRate, getTaxableAmount) {var taxable = amount;taxable = getTaxableAmount(amount);var tax = taxable * taxRate;return (isNaN(tax))? "Invalid calculation." : tax;};
Add code to check that getTaxableAmount is a function before calling it.
How could the following code be improved?var calculateSalesTax = function(amount, taxRate, getTaxableAmount) {var taxable = amount;taxable = getTaxableAmount(amount);var tax = taxable * taxRate;return (isNaN(tax))? "Invalid calculation." : tax;}; Question options:
Add code to check that getTaxableAmount is a function before calling it.
Code example 14-2window.onload = function() {var topSites = ["Google", "Facebook", "Twitter"];var links = $("top_sites").getElementsByTagName("a");for (var i in topSites) {links[i].text = topSites[i];links[i].onclick = (function(name) {return function() {alert("You clicked on " + name);};})(topSites[i]);}}; (Refer to code example 14-2) If the onclick event handlers for the links were attached directly instead of within an IIFE, what would happen?
All the links would display the name of the last site in the array.
What will happen first as soon as the page that contains the following code loads?window.onload = function() {alert("Welcome to the Calculate Cost page!");$("ship").onclick = shipCost();};
An alert dialog box will display with the message "Welcome to the Calculate Cost page!".
Which of the following statements about associative arrays is true?
An associative array uses strings as the indexes.
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
Given the following lines of code, what will be displayed in successive dialog boxes?var answers = [ "C", "B", "D", "A" ];delete answers[3];for ( var i in answers ) {alert(answers[i]);}
C, B, D
Given the following lines of code, what will be displayed in successive dialog boxes?var answers = [ "C", "B", "D", "A" ];delete answers[3];for ( var i = 0; i < answers.length; i++ ) {alert(answers[i]);}
C, B, D, undefined
What happens when you create an array of one or more elements but don't assign values to those elements?
Each element is set to undefined.
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
Which of the following statements about function declarations and function expressions is NOT true?
Function declarations cannot return a value.
If a numerical operation returns a number greater than the largest possible JavaScript value, it returns
Infinity
Code example 14-2window.onload = function() {var topSites = ["Google", "Facebook", "Twitter"];var links = $("top_sites").getElementsByTagName("a");for (var i in topSites) {links[i].text = topSites[i];links[i].onclick = (function(name) {return function() {alert("You clicked on " + name);};})(topSites[i]);}}; (Refer to code example 14-2) When the IIFE is invoked, what happens to the array element (topSites[i]) that's passed as an argument
It becomes the name parameter.
What does the optional limit parameter of the split() method do?
It specifies the maximum number of elements in the new array.
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,
What is displayed by the alert dialog box after the following code executes?var name = "Donny,Duck";var index = name.indexOf(","); var lastName = name.substr(index + 1, name.length - 1);;alert("Last name: " + lastName);
Last name: Duck
If the current date is Monday, February 26, 2017, what will be displayed by the alert dialog box after the following code executes?var thisDay = new Date(); alert(thisDay.toDateString());
Mon Feb 26 2017
What does the code that follows do?var image = new Image();image.src = "logo.jpg";
Preloads "logo.jpg".
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.
What does the second statement that follows do?var numbers = [1, 2, 3, 4];numbers.length = 0;
Removes all the elements in the array.
Which of the following is NOT true about the script mode feature of ECMAScript 5?
Script mode is supported by all older browsers.
What does the code that follows do?$("email").firstChild.nodeValue = "Entry is invalid.";
Sets the text for the element with "email" as its id attribute.
In the following code, what does the bind method do?var tax = {rate: 0.075,calc: function(sub) { return sub + (sub * this.rate)).toFixed(2); },displayFullPrice: function(subtotal) {return function() {alert(this.calc(subtotal));}.bind(this);} };
Sets the value of the this keyword in the displayFullPrice method to the tax object.
Code example 14-1var createClickCounter = function() {var count = 0;var clickCounter = function() {count++;console.log(this.id + " + count is " + count);};return clickCounter;};window.onload = function() {$("btnCount").onclick = createClickCounter();}; (Refer to code example 14-1) Why is there a pair of parentheses after createClickCounter in the statement in the onload event?
So the outer function runs and returns the definition of the inner function.
Code example 14-1var createClickCounter = function() {var count = 0;var clickCounter = function() {count++;console.log(this.id + " + count is " + count);};return clickCounter;};window.onload = function() {$("btnCount").onclick = createClickCounter();}; (Refer to code example 14-1) Which of the following statements about this code is not true?
The count variable stays alive after the outer function runs and can be accessed by outside code.
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);}
The factorial of 3 = 6
Which of the following statements about the sort() method of an array is NOT true?
The function passed to the sort() method returns a value of true or false.
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);
The scores array: 70,20,35,15,40
What happens when a string doesn't include the separator that's specified in the parameter of the split() method?
The split() method returns an array that contains the string as its only element.
Code Example 4-1var name = prompt("Enter the name to print on your tee-shirt");while (name.length > 12) {name = prompt("Too long. Enter a name with fewer than 12 characters.");}alert("The name to be printed is " + name.toUpperCase()); (Refer to Code Example 4-1) What will happen if the user enters Willy Shakespeare at the first prompt?
The user will be prompted to enter a different name
Code example 13-1var evt = {attach: function(node, eventName, func) {if (node.addEventListener) {node.addEventListener(eventName, func);} else if (node.attachEvent) {node.attachEvent("on" + eventName, func);}},detach: function(node, eventName, func) {if (node.removeEventListener) {node.removeEventListener(eventName, func);} else if (node.detachEvent) {node.detachEvent("on" + eventName, func);}},preventDefault: function(e) {e = e || window.event;if ( e.preventDefault ) { e.preventDefault(); }else { e.returnValue = false; }}}; (Refer to code example 13-1.) This is the code for a cross-browser compatible library for working with events. It contains
Three methods
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
After the code that follows executes, the alert dialog box will display var userCost = 29.94999;alert("Your cost is $ " + parseFloat(userCost.toFixed(2)));
Your cost is $ 29.95
To make sure that the HTML and CSS for a web page are interpreted the same way by all browsers, you can use
a Javascript shiv and the normalize.css style sheet
The following code is an example ofvar getInvoice = function( subtotal, taxRate ) {var invoicePrototype = {getTotal: function() {return this.subtotal + (this.subtotal * this.taxRate);}};var invoice = Object.create( invoicePrototype );invoice.subtotal = subtotal;invoice.taxRate = taxRate;return invoice;}
a factory function
Within a CSS style rule, a property declaration inculdes
a property and a value
The following code will move the focus to window.onload = function() {$("join_up").onclick = signUp;$("user_first_name").focus();};
a textbox with id = "user_first_name"
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
When you use the relational operators, you can compare
a variable with a literal value a variable with another variable a variable with an arithmetic expression
to make a website available to other computers over a network, the website is stored on
a web server
Code Example 4-2var add = function( x, y ) {return ( x + y );}alert( add (5, 3) ); (Refer to Code Example 4-2) The function in this example
accepts 2 parameters and returns 1 value
Given the following code, which of the following statements displays "John Smith is 29"?var employee = [];employee["name"] = "John Smith";employee["age"] = 29;
alert(employee["name"] + " is " + employee["age"]);
What elements would the style rule that follows apply to? .red { color: red; }
all elements with the class named red
When a client requests a dynamic web page, the HTML is generated by
an application server
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
In a simple assignment statement, you use the _____________________ operator.
assignment
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".
The condition for a while loop is tested
before the statements in the loop are executed
Which HTML event occurs when an element on the page loses focus?
blur
The class attribute
can be used by CSS to apply the same formatting to more than one HTML element
Which of the following statements is false? A JavaScript identifier
can start with a number
The following codevar display_error = function(message) {alert("Error: " + message);}
creates a function and stores it in a variable named display_error
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
Code Example 4-2var add = function( x, y ) {return ( x + y );}alert( add (5, 3) ); (Refer to Code Example 4-2) The alert method in this example
displays a dialog box with a value of 8
Given a Date object named due_date, which of the following statements sets the month to February?
due_date.setMonth(1);
Code example 13-1var evt = {attach: function(node, eventName, func) {if (node.addEventListener) {node.addEventListener(eventName, func);} else if (node.attachEvent) {node.attachEvent("on" + eventName, func);}},detach: function(node, eventName, func) {if (node.removeEventListener) {node.removeEventListener(eventName, func);} else if (node.detachEvent) {node.detachEvent("on" + eventName, func);}},preventDefault: function(e) {e = e || window.event;if ( e.preventDefault ) { e.preventDefault(); }else { e.returnValue = false; }}}; (Refer to code example 13-1.) This is the code for a cross-browser compatible library for working with events. To attach an event handler named toggleH2 to the click event of a heading with "q1" as its id, you code which of the following statements:
e.attach($("q1"),onclick,toggleH2;
Now that HTML5 is used by all modern browsers, the HTML div element should be used primarily for grouping
elements for JavaScript and jQuery applications
Given an event object that's stored in a variable named evt, which of the following statements will cancel the default action in modern browsers?
evt.preventDefault();
When the statement that follows is executed, JavaScript var rate = parseFloat(document.getElementById("rate").value);
executes the getElementById() method, gets the value property of the resulting object, and executes the parseFloat() method on that value
Which method accepts a function that is executed once for each element and returns a new array that contains the elements that meet the condition specified in the function?
filter()
Which of these for statements displays even numbers from 0 to 10?
for ( var i = 0; i <= 10; i += 2 ) { alert( i ); }
The type of loop that provides for varying the value of an index (or counter) is a
for loop
Which of the following is a valid function declaration for a function named getUserAge() that accepts one parameter?
function getUserAge(user)
Code Example 4-3var tax = .07;var getCost = function(itemCost, numItems) {var subtotal = itemCost * numItems;var tax = 0.06;var total = subtotal + subtotal * tax;return (total);}var totalCost = getCost(25.00, 3);alert("Your cost is $" + totalCost.toFixed(2) + " including a tax of " +tax.toFixed(2)); (Refer to Code Example 4-3) Which variable represents the function expression?
getCost
Each function has a this keyword whose value depends on
how the function was invoked
When you "comment out" JavaScript code, the code is __________________________ when the page is tested.
ignored
Code example 14-1var createClickCounter = function() {var count = 0;var clickCounter = function() {count++;console.log(this.id + " + count is " + count);};return clickCounter;};window.onload = function() {$("btnCount").onclick = createClickCounter();}; (Refer to code example 14-1) The count variable of the outer function is
in private state.
If possible, the parseInt method converts the string that's passed to it to a/an _____________________________.
integer
Which of the following will test whether a Boolean variable named isValid is true?
isValid == true isValid !isValid == false
A binary search is better for large arrays than a sequential search because
it discards half the array on each comparison.
Because window is the global object of JavaScript,
it is not necessary to code the object name before the method name
A cascading method can be chained with other methods. This style of coding is sometimes called fluent because
it reads like a sentence and is easy to understand
An IIFE should always be coded within parentheses because
it's a coding convention that lets other programmers know it's an IIFE.
Which method returns the elements of an array in a string separated by a comma?
join()
Which keyboard event occurs when a key has been released?
keyup
Which mouse event occurs when the mouse pointer hovers over an HTML element?
mouseover
When you test an application with Chrome's developer tools and a breakpoint is reached, you can view the current data by
moving the mouse pointer over the name of a variable in the Sources panel
When writing a recursive function, what kind of function expression should you use to make sure the function will always be able to call itself.
named
The equal to (==) and not equal to (!=) operators should
not be used to compare floating-point numbers
In the code that follows, document is a/andocument.getElementById("emailAddress");
object
In the code that follows, window is a/an ____________________________.window.prompt("Enter your name");
object
If an arithmetic expression isn't evaluated the way you want it to be due to the order of precedence, you can override that order by using ____________________.
parentheses
What can you use to clarify the order of relational and logical operations in a conditional expression?
parentheses
What sequence of components does an HTTP URL consist of before the filename?
protocol, domain name, path
Which method accepts a function that combines all the elements in the array and then returns the resulting value?
reduce()
A for-in loop doesn't
require expressions to intialize, test, and increment an index counter
To provide JavaScript in the body of an HTML document, you code an HTML __________________ element that contains the JavaScript.
script
How can you clear a check from a Checkbox object?
set its checked property to false
Which of the following statements runs the newTimer function every 3 seconds?
setInterval(newTimer, 3000);
Which of the following statements runs the newTimer function once after 3 seconds?
setTimeout(newTimer, 3000);
Which of the following methods of the Array object accepts a callback function as an argument?
sort
Code example 16-1var testScores = [];testScores[0] = [80, 82, 90, 87, 85];testScores[1] = [79, 80, 74, 82, 81];testScores[2] = [93, 95, 89, 100, 85];testScores[3] = [60, 72, 65, 71, 79]; (Refer to code example 16-1) Which of the following returns a value of 89?
testScores[2][2]
Which of the following statements performs a case-insensitive comparison of the strings named text1 and text2?
text1.toLowerCase() == text2.toLowerCase()
A cross-browser compatible method for attaching an event handler must provide parameters for
the HTML node, the event, and the event handler
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
When you test an application with Chrome's developer tools and a breakpoint is reached, you can click
the Step Into button to execute the current statement and move to the next statement
Code example 13-1var evt = {attach: function(node, eventName, func) {if (node.addEventListener) {node.addEventListener(eventName, func);} else if (node.attachEvent) {node.attachEvent("on" + eventName, func);}},detach: function(node, eventName, func) {if (node.removeEventListener) {node.removeEventListener(eventName, func);} else if (node.detachEvent) {node.detachEvent("on" + eventName, func);}},preventDefault: function(e) {e = e || window.event;if ( e.preventDefault ) { e.preventDefault(); }else { e.returnValue = false; }}}; (Refer to code example 13-1.) This is the code for a cross-browser compatible library for working with events. In the code for the attach method, the if clause provides for modern browsers and the else if clause provides for older IE browsers. This shows that older browsers require the use of
the attachEvent method of a node object and the prefix "on" for the event name
To remove the focus from a control, what method do you use?
the blur method
What event occurs when the user selects a new item from a select list?
the change event
The delete operator deletes
the contents of an element in an array
Code example 13-1var evt = {attach: function(node, eventName, func) {if (node.addEventListener) {node.addEventListener(eventName, func);} else if (node.attachEvent) {node.attachEvent("on" + eventName, func);}},detach: function(node, eventName, func) {if (node.removeEventListener) {node.removeEventListener(eventName, func);} else if (node.detachEvent) {node.detachEvent("on" + eventName, func);}},preventDefault: function(e) {e = e || window.event;if ( e.preventDefault ) { e.preventDefault(); }else { e.returnValue = false; }}}; (Refer to code example 13-1.) This is the code for a cross-browser compatible library for working with events. In the code for the preventDefault method, the first statement sets e equal to either
the event object that's passed to the event handler or the window.event object
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
When you call a constructor, you create an instance of the object type that inherits
the methods of that type
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
What does the length property of an array return?
the number of elements in the array
When you develop a web page, you should use HTML to provide
the structure and content for the page
What method of the Number object returns a string with the number rounded to the specified number of decimal places?
the toFixed method
For a Textarea object, what property do you use to get the text that has been entered into the text area?
the value property
When a client requests a static web page, the HTML is generated by
the web browser
What value is returned by the following expression? !isNaN("12.345")
true
To load a web page into a web browser, you can
type the URL of the web page into the browser's address bar
Which method adds one or more elements to the beginning of an array?
unshift()
Which of the following statements is NOT a valid way to create a date object named birthday?
var birthday = "12/2/1978";
Which of the following will create an event handler that is attached to the mouseout event for a textbox with id = "username" so that the user's entry, formatted in all lowercase, will be displayed in an alert? Assume the following $ function has already been coded in the page:var $ = function(id) {return document.getElementById(id);};
var getUserName = function() {var name = $("username").value;alert("Your username is " + name.toLowerCase());};window.onload = function() {$("username").onmouseout = getUserName;};