javascript test 1 study

Ace your homework & exams now with Quizwiz!

Which of the following patterns can be used to validate a five digit ZIP code?

/^\d{5}$/

Code example 17-2 var Employee = function(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; };Employee.prototype.getFullName = function() {return this.firstName + " " + this.lastName;}; (Refer to code example 17-2) This code creates an Employee object type that contains

1 constructor, 2 properties, and 1 method

Code example 17-1 var invoice = { taxRate: 0.0875, getSalesTax: function( subtotal ) {return ( subtotal * this.taxRate );}, getTotal: function ( subtotal ) {return subtotal + this.getSalesTax( subtotal );}}; (Refer to code example 17-1) This code creates an object with

1 property and 2 methods

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 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 = 0; i < totals.length; i++) { 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.

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

4

Code example 16-1 var 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

Which HTML element does NOT have a default action associated with the click event?

<img>

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.

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.

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

Consider the following code example: $(document).ready( function() { $(":text, :password").after("<span>*</span>"); . . $("#member_form").submit( function(event) { var isValid = true; . . var password = $("#password").val(); if (password == "") { $("#password").next().text("This field is required."); isValid = false; } else if ( password.length < 6) { $("#password").next().text("Must be 6 or more characters."); isValid = false; } else { $("#password").next().text(""); } . . } );});

Cancel the submission of the form if the the entry for the password field is invalid

Code Example 7-2 JavaScript code for an Image Swap 1. var $ = function(id) { 2. return document.getElementById(id); 3. }; 4. window.onload = function() { 5. var listNode = $("image_list"); 6. var captionNode = $("caption"); 7. var imageNode = $("main_image"); 8. var imageLinks = listNode.getElementsByTagName("a"); 9. var i, image, linkNode, link; 10. for ( i = 0; i < imageLinks.length; i++ ) { 11. linkNode = imageLinks[i]; 12. image = new Image(); 13. image.src = linkNode.getAttribute("href"); 14. linkNode.onclick = function(evt) { 15. link = this; 16. imageNode.src = link.getAttribute("href"); 17. captionNode.firstChild.nodeValue = link.getAttribute("title"); 18. if (!evt) { evt = window.event; } 19. if (evt.preventDefault) { evt.preventDefault(); } 20. else { evt.returnFalse = false; } 21. }; 22. } 23. imageLinks[0].focus(); 24. }; (Refer to Code Example 7-2) What would happen if lines 18 through 20 were omitted?

Clicking on a link would open a new browser window or tab and display the image specified by the href attribute of the link.

To start and stop a slide show, you must do all but one of the following. Which one is it?

Code an event handler for the click event of the slides

What does the statement that follows do?$("#current_image").finish().animate({ height: "200%", width: "200%" });

Completes all animations for the selected element immediately, clears the queue for that element, and then executes the animate() method.

What does an easing do?

Controls the way an effect or animation is performed.

Which native object type can you NOT create by assigning a literal value to a variable?

Date

What does the statement that follows do?$("#message").delay(10000).fadeOut(2000);

Delays the start of the fadeOut() method for 10 seconds

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.

When working with jQuery effects, what does chaining do?

Executes two or more jQuery effects in a row

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.

What does the following jQuery code do?$("h2").prev();

Gets the previous sibling of the selected h2 element

Code example 17-2 var Employee = function(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; };Employee.prototype.getFullName = function() {return this.firstName + " " + this.lastName;}; (Refer to code example 17-2) The following code displays var employee = new Employee("Grace", "Hopper"); alert (employee.firstName);

Grace

Code example 17-2 var Employee = function(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; };Employee.prototype.getFullName = function() {return this.firstName + " " + this.lastName;}; (Refer to code example 17-2) The following code displaysvar employee = new Employee("Grace", "Hopper");employee.lastName = "Murach";alert (employee.getFullName());

Grace Murach

The load() method requests and returns

HTML

Cross-browser compatibility is a serious development issue because Internet Explorer and the other browsers don't always interpret

HTML, CSS, and JavaScript the same way

Assume that you have an object of the Object type named employee. Assume also that this object only has two properties named firstName and lastName. What does the following code do? employee.streetAddress = "123 Main Street";

It adds a property named streetAddress to the employee object.

Code example 10-2 $(document).ready(function() {$("#member_form").submit(function(event) { var isValid = true;. .var password = $("#password").val().trim(); if (password == "") { $("#password").next().text("This field is required."); isValid = false;} else if ( password.length < 6) { $("#password").next().text("Must be 6 or more characters.");isValid = false;} else { $("#password").next().text("");}$("#password").val(password);.. if (isValid == false) { event.preventDefault(); }});}); (Refer to code example 10-2) What does the preventDefault() method in this code do?

It cancels the submit() event method of the form.

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?

It creates a timer that counts down from 10 to 1 and displays "Blastoff!" in the span element when the counter variable reaches 0.

Code example 10-1 $(document).ready(function() { $("#contact_me").change(function() { if ($("#contact_me").attr("checked")) { $(":radio").attr("disabled", false);} else { $(":radio").attr("disabled", true);}});}); (Refer to code example 10-1) What does this code do?

It disables or enables all radio buttons when an element is checked or unchecked.

In the following code, what does the line of code in the else clause do? $(document).ready(function() { $("#join_list").click(function() { // join_list is a regular button if ( $("email_address").val() == "") { alert("Please enter an email address."); } else { $("#email_form").submit();}});});

It triggers the submit() event method.

When you use Ajax to get data for a web page from the server, what is used to send the request?

JavaScript

To allow a user to enter a value into a dialog box, use the

JavaScript prompt() method

Given the code that follows, what will the alert statement display? var names = ["Mike", "Anne", "Joel"];names.push("Ray", "Pren");var removedName = names.pop();alert (names.toString());

Mike,Anne,Joel,Ray

Code example 17-1 var invoice = { taxRate: 0.0875, getSalesTax: function( subtotal ) {return ( subtotal * this.taxRate );}, getTotal: function ( subtotal ) {return subtotal + this.getSalesTax( subtotal );}}; (Refer to code example 17-1) This code creates an object of the

Object type

What object defines a pattern that can be searched for in a string?

Regular Expression

What does the following jQuery code do?$("#image").attr("src", imageURL);

Sets the value of the src attribute for the element with an id of "image" to the value in a variable named imageURL

Which of the following statements is true?

Some browsers provide automatic data validation for some HTML5 input controls.

What does the statement that follows do?$("#current_image").stop(true).animate({ height: "200%", width: "200%" });

Stops the current animation on the selected element, clears the queue for that element, and then executes the animate() method.

Which of the following is a true statement about objects?

The Number type inherits the methods of the Object type.

Which of the following is NOT true about using Chrome's developer tools to test an application?

The Sources panel will display a list of all runtime errors in the order they appear in your code.

What is the difference between the break statement and the continue statement in a loop?

The break statement ends a loop; the continue statement ends the current iteration of a loop.

Code example 9-1 $("#faqs h1").animate({ fontSize: "250%", left: "+=125" }, 3000, function() {$("#faqs h2").next().fadeIn(1000).fadeOut(1000);}); (Refer to code example 9-1) What animation is performed by the properties map of the animate() method?

The font size of the selected element is changed to 250% of the default and the element is moved right 125 pixels.

Which of the following statements is true after the code below is executed? var today = new Date(); // assume date is 6/1/2017 var now = today; today.setFullYear(2018);

The getFullYear() method of both variables returns 2018.

Code example 8-1 $("#faqsh2").click(function() {$(this).toggleClass("minus");if ($(this).attr("class") != "minus") {$(this).next().hide();}else {$(this).next().show();}}); (Refer to code example 8-1) What does the this keyword refer to in this code?

The h2 heading that was clicked

ass

The mpg library contains code that depends on the jQuery library.

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

Code example 9-1 $("#faqs h1").animate({ fontSize: "250%", left: "+=125" }, 3000, function() {$("#faqs h2").next().fadeIn(1000).fadeOut(1000);}); (Refer to code example 9-1) What animation is performed by the callback function of the animate() method?

The sibling that follows each of the selected h2 elements is faded in and then faded out.

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

Ajax was originally designed to be used with

XML

By default, the $.get() method requests and returns

XML

Code Example 4-DOH var totalCost = getCost(25.00, 3); alert(totalCost); var getCost = function(itemCost, numItems) {var subtotal = itemCost * numItems;var tax = 0.06;var total = subtotal + subtotal * tax;return (total);} (Refer to Code Example 4-DOH) This code contains an error. Identify the error.

You cannot call getCost before it has been defined because it uses a function expression instead of function declaration.

Code Example 2-1 1. var myAge, newAge; 2. myAge = prompt("How old are you?"); 3. myAge = parseInt(myAge); 4. newAge = 18 - myAge; 5. alert("You will be eligible to vote in " + newAge + " years"); (Refer to Code Example 2-1) What would be returned if the user entered 14.78 at the prompt?

You will be eligible to vote in 4 years

Code Example 2-1 1. var myAge, newAge; 2. myAge = prompt("How old are you?"); 3. myAge = parseInt(myAge); 4. newAge = 18 - myAge; 5. alert("You will be eligible to vote in " + newAge + " years"); (Refer to Code Example 2-1) What would be returned if the user entered "fifteen" at the prompt?

You will be eligible to vote in NaN years

Which of the following is used in a regular expression pattern as an escape character?

\

To execute code after a jQuery effect has finished, you can use

a callback function

If you want the block of code in a loop to be executed at least once, you would normally use

a do-while loop

When you use the animate() method, what must you code to determine how long the animation will last?

a duration parameter

When you create an object, you can add a method to the object by pairing a property name with

a function definition

When you use the animate() method, what must you code to define the animation?

a properties map

Consider the following code example: var add = function( x, y ) { return ( x + y );}alert( add (5, 3) ); The function in this example

accepts 2 parameters and returns 1 value.

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>

all of the above

Which of the following events occurs when the user moves the mouse pointer over an element and then clicks on it?

all of the above

When a client requests a dynamic web page, the HTML is generated by

an application server

Code example 10-1 $(document).ready(function() { $("#contact_me").change(function() { if ($("#contact_me").attr("checked")) { $(":radio").attr("disabled", false);} else { $(":radio").attr("disabled", true);}});}); (Refer to code example 10-1) What do the jQuery selectors in this code select?

an individual element by id and all radio buttons

jQuery is

an open source JavaScript library

In JavaScript, all functions are objects, and all of the arguments passed to a function

are stored in the arguments property

For the following code, an event handler named investmentChange is var investmentChange = function() {var years = parseInt( $("years").value );alert("Years: " + years);}; window.onload = function() {$("investment").onchange = investmentChange;};

attached to the onchange event of a control with an id of "investment"

Three of the common CSS selectors select

by element type, id attribute, and class attribute

The easiest way to create a timer that will repeat its function at intervals but will begin immediately is to

call the function before you create the timer

What event occurs when the user selects a new item from a select list?

change

You use the animate() method to

change CSS properties for selected elements

Code example 15-1 var cookie = "username=mike2009"; cookie += "; max-age=" + 365 * 24 * 60 * 60; cookie += "; path=/"; document.cookie = cookie; (Refer to code example 15-1.) This code

creates a cookie that's stored for 1 year

Code example 15-1 var cookie = "username=mike2009"; cookie += "; max-age=" + 365 * 24 * 60 * 60; cookie += "; path=/"; document.cookie = cookie; (Refer to code example 15-1.) This code

creates a cookie with a name of "username" and a value of "mike2009"

The following code function display_error(message) {alert("Error: " + message);}

creates a function named display_error

var display_error = function ( message ) { alert("Error: " + message);}

creates an anonymous 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

A jQuery selector includes all but one of the following. Which one is it?

dot operator

Which of the following methods would you use to execute a method for each element in an array?

each()

Which of the following do you use to attach an event handler?

event method

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 property would you use to get the node that contains the content for an element?

firstChild

JSONP provides a way to

get data from a server in a different domain

Code Example 4-3 var 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

Which method of the Document interface retrieves an array of all the elements of the specified type?

getElementsByTagName()

Which of the following statements goes back one step in the URL history?

history.back();

Each function has a this keyword whose value depends on

how the function was invoked

Which property of the location object can be used to retrieve the complete URL?

href

When creating a timer, the delay or interval is specified

in milliseconds

When the code that follows is executed, a message is displayed if the value the user enters var userEntry = (prompt("Enter cost:");if (isNaN(userEntry) || userEntry > 500 ) {alert ("Message");}

isn't a number or the value in userEntry is more than 500

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

JSON is a popular format for Ajax applications because

its data is easier to parse than XML

Web storage stores data in the browser in

key/value pairs

Which of the following methods is not one of the methods that trigger events?

leave()

The arguments property

lets a function accept a variable number of arguments

Code Example 7-2 JavaScript code for an Image Swap 1. var $ = function(id) { 2. return document.getElementById(id); 3. }; 4. window.onload = function() { 5. var listNode = $("image_list"); 6. var captionNode = $("caption"); 7. var imageNode = $("main_image"); 8. var imageLinks = listNode.getElementsByTagName("a"); 9. var i, image, linkNode, link; 10. for ( i = 0; i < imageLinks.length; i++ ) { 11. linkNode = imageLinks[i]; 12. image = new Image(); 13. image.src = linkNode.getAttribute("href"); 14. linkNode.onclick = function(evt) { 15. link = this; 16. imageNode.src = link.getAttribute("href"); 17. captionNode.firstChild.nodeValue = link.getAttribute("title"); 18. if (!evt) { evt = window.event; } 19. if (evt.preventDefault) { evt.preventDefault(); } 20. else { evt.returnFalse = false; } 21. }; 22. } 23. imageLinks[0].focus(); 24. }; (Refer to Code Example 7-2) Which lines of code attach an event handler for the click event of each link?

line 14 - 21

The reload() method of the location object has an optional force parameter. If it's set to true, the browser

loads the page from the server

Which of the following statements gets the same result as this statement?localStorage.name = "Grace";

localStorage.setItem("name", "Grace");

Which of the following statements stores an item in the browser indefinitely?

localStorage.setItem("name", "Grace");

Which attribute of a cookie do you set to create a persistent cookie?

max-age

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

You can create an instance of a native object type using which keyword?

new

Which property of a text node would you use to set the value of that node?

nodeValue

Which of the following is allowed in a cookie's value?

number

In the code that follows, window is a/an window.prompt("Enter your name");

object

Object chaining works because each method returns the appropriate

object

What is displayed when the following code executes? var numbers = ""; for ( var i = 1; i <= 30; i++ ) { if( i % 2 === 0 ) { continue;} else { numbers += i + " ";} } alert(numbers);

odd numbers between 1 and 30

Which method removes the last element from the end of an array?

pop()

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

What are the values of the two variables when the following code executes? var result1 = (1 == "1"); var result2 = (1 === "1");

result1 is true and result2 is false

The childNodes property of the Node interface

returns an array of Node objects that represent the child nodes of a node

A cascading method is one that

returns the object referred to by the this keyword

Which of the following types of errors will cause an application to stop executing?

runtime error

You include the jQuery library in your website by coding a

script element

Which property of the location object can be used to retrieve the query string from the URL?

search

The max-age attribute of a cookie is specified in

seconds

How can you clear a check from a Checkbox object?

set its checked property to false

To create a child object that inherits methods from a parent object using a constructor, you

set the prototype object equal to an instance of the object you want to inherit

Which of the following statements runs a function named newTimer every 3 seconds?

setInterval(newTimer, 3000);

Which of the following statements runs a function named newTimer once after 3 seconds?

setTimeout(newTimer, 3000);

You can use a handler for the submit event of a form to validate data when the user clicks a

submit button

Which method of a regular expression searches a string and returns true if the pattern is found?

test()

Code example 16-1 var 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 code statements sets the text of an element?

text(value)

If you want to run a callback function when an Ajax request fails, you need to use

the $.ajax() method

If you want to use JSONP with an Ajax request, you need to use

the $.ajax() method

After the statement that follows is executed, rateText represents var rateText = document.getElementById("rate");

the HTML element with "rate" as its id attribute

When you use Ajax to get more data for a web page,

the XHR object can include data that tells the server what data to return

What property of the Radio object is used to determine if a radio button is selected?

the checked property

What does the evt variable refer to in this code? $("#faqs h2").click(function(evt) {evt.preventDefault();};

the event object

The primary difference between the $.get() and $.post() methods is

the method that's used to send the data

When you call a constructor, you create an instance of the object type that inherits

the methods of that type

What does the length property of an array return?

the number of elements in the array

The this keyword in a method of an object usually refers to

the object itself

One benefit of using Ajax to get data for a web page from the server is that

the page doesn't have to be reloaded

If you use a short-circuit operator to combine two expressions

the second expression is evaluated only if it can affect the result

var rateText = document.getElementById("rate").value;

the string type value of what was entered in the HTML element with "rate" as its id attribute

An HTTP response is sent from

the web server to the client

In a web browser, the object that's always available to JavaScript so you don't have to code its name when you call one of its methods is

the window object

When you create an object type with a constructor, you add the object's methods

to the prototype object

Which of the following methods would you use to remove a class if it's present or add a class if it isn't present?

toggleClass()

Which of the following methods removes all the spaces before and after an entry in a text box?

trim()

What value is returned by the following expression? !isNaN("12.345")

true

Which method adds one or more elements to the beginning of an array?

unshift()

To avoid potential errors caused by using variables that are not properly declared, you should

use strict mode

If you do not want the user to be allowed to enter data into a textbox,

use the disabled property to gray out the textbox

Which of the following code statements gets the value of a text box?

val()

What property would you use to get the text that has been entered into a text area?

value

Code example 17-1 var invoice = { taxRate: 0.0875, getSalesTax: function( subtotal ) {return ( subtotal * this.taxRate );}, getTotal: function ( subtotal ) {return subtotal + this.getSalesTax( subtotal );}}; (Refer to code example 17-1) Assume that a variable named invoiceSubtotal contains the subtotal for an invoice. How would you write code that calls the getTotal method and assigns the result that's returned to a new variable named invoiceTotal?

var invoiceTotal = invoice.getTotal(invoiceSubtotal);

Which of the following is a valid statement for declaring and initializing a variable named length to a starting value of 120?

var length = 120;

Though it is possible to use JavaScript for all of the below contexts, specifically for this class our Javascript code will be run by the:

web browser

The index value of the first element in a JavaScript array is

zero


Related study sets

Chapell/Meek (Licensure and Ordination), Chapell Meek (Licensure)

View Set

Chapter 13: Billing and Collections

View Set

Surgery Book MCQs - Quiz 1 (Chapters: 1-10)

View Set

CHEM 108 Test: Atomic Structures

View Set

arizona laws and rules pertinant to insurance

View Set

Làm gì mà + tính từ + thế / ເຮັດຫຍັງຈິ່ງ + ຄຳຄຸນນາມ + ແທ້

View Set