Web Programming C298 (JavaScript)

¡Supera tus tareas y exámenes ahora con Quizwiz!

Which JavaScript code segment indicates that either the variable myVar is not zero, or the variable myVar2 is less than or equal to 20?

!(myVar == 0) || myVar2 <= 20; The correct expression is !(myVar == 0) || myVar2 <= 20;. The initial ! operator means NOT but it applies only to the first statement in parentheses, not both statements. The || operator means OR. The && operator would indicate that both statements apply, rather than one or the other. The presence of two ! operators in the first operation !(myVar != 0) would indicate a double negative, meaning that the first statement is true rather than false.

Which of the following expressions evaluates to true?

"90" !== 90 The expression that will evaluate to true is "90" !== 90. In strict comparison, not only the value but also the data type of both operands must be equal (===) or not equal (!==). Therefore, same data type (or different data type for !==) is required for the expression to evaluate to true. In non-strict comparison (==), JavaScript will attempt to convert the operands of different types in an expression to the same type, but same data type is not required for the expression to evaluate to true.

Consider the following XHTML code: <a name="here">Click</a> Which JavaScript statement will produce the above code?

"Click".anchor("here"); The correct statement is "Click".anchor("here");. The anchor function works by creating a new anchor with the name assigned to the parameter passed to it, and the calling string is the displayed text.

Programmers refer to attributes and values as

"properties."

Which JavaScript operator indicates concatenation?

+ Concatenation is used frequently in JavaScript to combine text strings. Depending on the operands, + is the operator for arithmetic addition or for string concatenation. When used for concatenation, the plus (+) operator combines the operands into a single string.

Which of the following operators is an assignment operator?

+= The += operator is an assignment operator. Expressions with assignment operators assign the result of the expression on the right of the operator to the left operand. All arithmetic operators become assignment operators when placed in front of the = character. The == operator is a comparison operator. The modulus operator (%) is an arithmetic operator that performs division and calculates the remainder. The + operator can be an arithmetic operator to perform addition or a string operator to perform concatenation.

hich regular expression pattern will match a number in the form 123-45-6789?

/\d{3}-\d{2}-\d{4}/ The correct regular expression pattern is: /\d{3}-\d{2}-\d{4}/. This expression uses the correct syntax of \d to match a digit, the number digits to match in brackets and the two hyphens.

Consider the following code: var x = 0; do { document.write(x + " "); } while (x >10) How many times will the code inside the curly brackets execute?

1 time The code will execute one time. The do...while statement operates like the while statement, with one key difference: The do...while statement does not check the conditional expression until after the first time through the loop, guaranteeing that the code within the curly braces will execute at least once.

Your boss needs a way to match order numbers that are input by visitors to your Web site. The order numbers used by the company have a specific format. You offer to write a script to match order number formats that are input. You write the following regular expression for the script: /\d{3}-?\D{3}-?\d{2}-\D{2}/ Which of the following order numbers will this regular expression match?

123abc45-de This regular expression will find a match in the order number 123abc45-de. The expression is looking for a pattern of three digits, followed by an optional hyphen, then three non-digit characters, then another optional hyphen, then two digits, then a required hyphen and finally two non-digit characters. d = digits D = non-digit characters ? = optional

Consider the following code: for (var x = 0; x < 26; x+=5) { if (x == 10) continue; document.write(x + "<br/>"); } How many lines will this statement output to the document?

5 lines This statement will output 5 lines to the document. The continue statement is used to force the flow of control back to the top of a loop. You can think of continue as a "skip" or bypass command. When execution hits a continue statement, all statements between it and the end of the loop block are skipped, and execution returns to the top of the loop. The test condition for the loop is then evaluated to determine whether the loop should execute again. The continue statement can be used only within a for or a while loop. Notice that the x variable is initialized at 0 and 5 will be added to it on every iteration. When the value of x is 10, nothing will be printed.

Consider the following code: for (var x = 0; x < 26; x+=5) { document.write(x + "<br/>"); } How many lines will this statement output to the document?

6 lines This statement will output six lines to the document. Notice that the x variable is initialized at 0 and a value of 5 will be added to it on every iteration. The last value output will be 25, then no further lines will be output because the next value would be 30, which exceeds 26. The primary purpose of the for statement is to repeat a group of statements for some particular range of values. The format of a for statement is as follows: for (x; y; z) { //one or more statements }

You have a link on your Web page. You want to display a message in the status bar when a user hovers his mouse over the link. Which code will achieve these results?

<a href=http://www.CIWcertified.com onmouseover="status='Visit the CIW Web site.';return true;" onmouseout="status='';return true;">Visit CIW</a> An often-used window object property is status. The status property refers to the text string displayed in the status bar at the bottom of the browser window. You can change the window's status bar text at any time during a script by using the status property. One common approach is to use inline scripting to make changes to the status property from hyperlinks and form elements. For security reasons, some browsers are beginning to disallow any change in the status bar message to ensure that you know exactly where a link is pointing before you click it. For this reason, the status property may eventually be deprecated.

Which code snippet correctly scripts an event handler in an XHTML <body> tag to execute script immediately when an XHTML page is closed?

<body onunload = "alert('Hello.');"> The correct code is <body onunload = "alert('Hello.');">. The onunload event handler intercepts the unloading of a Web page and allows the developer to associate executable code with this event. The onunload keyword is added to the <body> tag as an attribute.

Which X/HTML tag corresponds to the document object in JavaScript?

<body> The X/HTML <body> tag corresponds to the document object in JavaScript. In any given window or frame, the document object is important. The document object provides the properties and methods to work with many aspects of the current document, including text, anchors, forms, links, page title, current location and URL, and the current background and foreground colors. The document object is a combination of the content and interface elements that constitute a Web page. The document object is defined when the <body> tag is evaluated in an X/HTML page. The object exists as long as the page is loaded.

Which example shows the correct generic syntax for the button object?

<input type="button" value="Text on Button" onclick="script to execute" /> Generic button syntax for the button object is as follows: <input type="button" value="Text on Button" onclick="script to execute" />

Document Object Model (DOM)

A W3C specification intended to render an X/HTML page or XML document as a programmable object.

floating-point calculation

A calculation in which the decimal point can move as needed to account for significant digits.

Consider the following JavaScript code: function helloWorld(){ myVar = "Hello World"; } helloWorld(); alert(myVar); What will be the result of this code?

A dialog box that displays: Hello World The result of this code will be a dialog box that displays Hello World. If you declare a variable within a function definition, the only way you can access or change it is from within that function. Once you declare a variable within a function, the variable is known as a local variable, and you cannot access its value from any other function except the one in which it was declared. Any variable that is created without the var keyword is global in scope, regardless of where that variable was created.

Consider the following JavaScript code: var subTotal = 1; var tax = 0.03; alert("The total is " + subTotal * (1 + tax)); What is the result of this code?

A dialog box that displays: The total is 1.03 The result of this code is a dialog box that displays: The total is 1.03. Often, when you report on a variable (for example, when using an alert box), it does not matter whether the variable is actually being cast or not. However, when performing mathematical operations, casting is very important because you need mathematical precedence, rather than concatenation, to occur.

Consider the following JavaScript code: function helloWorld(){ var myVar = "Hello World"; } alert(myVar); What will be the result of this code?

A dialog box that displays: undefined The result of this code will be a dialog box that displays undefined. If you declare a variable within a function definition, the only way you can access or change it is from within that function. Once you declare a variable within a function, the variable is known as a local variable, and you cannot access its value from any other function except the one in which it was declared.

In JavaScript, what is a reserved word?

A keyword that cannot be used for any other purpose in JavaScript code in JavaScript, a reserved word is a keyword that cannot be used for any other purpose in JavaScript code. JavaScript contains keywords that you must use to achieve specific results. JavaScript also contains reserved words that you cannot use for variables, functions, objects or methods. You cannot use JavaScript reserved words as names for objects. In addition, reserved words cannot be used for variable or function names. Keywords cannot be used as names for variables.

function

A named block of code that can be called when needed. In JavaScript, a function can return a value. The generic syntax for a function is as follows: function functionName(argument1, argument2, ...) { //statement(s) here } The keyword function must be typed as shown, in all lowercase letters. The curly braces must encompass any statements that are to execute as part of that function. Parentheses () must follow the user-defined function name. Define all your functions in the <head> element of your X/HTML page. That way, when the page is loaded into the browser, the functions will load before any user event can occur that might call the function. Also, your function definitions will be grouped together, which makes troubleshooting easier.

Which of the following best describes a function?

A named, organized block of code A user-defined function is a named, organized block of code that handles actions generated by user events. Functions enable you to write code and place it into a single unit that can perform a specific task repeatedly throughout the program, as needed. Parentheses () follow the function name and are used to receive arguments, but a function does not necessarily have to take or use any arguments. A function can receive as many arguments as it needs to perform its task.

What is an expression in JavaScript?

A part of a statement that is evaluated as a value An expression is a part of a statement that is evaluated as a value. The exception to this is an assignment expression, which assigns a value to a variable. An expression can use any combination of variables, literals, operators and other expressions.

Perl

A script programming language commonly used for Web server tasks and CGI programs.

loosely typed language

A scripting or programming language that does not require the developer to declare a variable's data type and allows a variable's data type to change. JavaScript is loosely typed.

array

A single variable with multiple values, which are indexed for easy referencing. In JavaScript, an array index is zerobased.

calling statement

A statement that transfers program execution to a subroutine, procedure or function. When the subroutine is complete, execution transfers back to the command following the call statement.

argument

A value or expression containing data or code that is passed on to a function or procedure. (often referred to as parameters) are pieces of data that the function receives and manipulates within the function. A function can receive as many arguments as it needs to perform its task.

In JavaScript, what is an argument?

A value passed into a function from outside the function An argument is a value passed into a function from outside the function. The curly braces in a function must encompass any statements that are to execute as part of that function. Parentheses () must follow the user-defined function name. These parentheses are used to receive arguments, but a function does not necessarily have to take or use them. Arguments (often referred to as parameters) are pieces of data that the function receives and manipulates within the function. A function can receive as many arguments as it needs to perform its task.

In JavaScript, what is a keyword?

A word used for specific results that cannot be used for any other purpose in JavaScript code In JavaScript, a keyword is a word used for specific results that cannot be used for any other purpose in JavaScript code. Keywords are the predefined identifiers that form the foundation of JavaScript. They perform unique duties such as declaring variables (var) and defining functions (function).

You are developing a Web application that relies on images and JavaScript for user interaction. You have included a <noscript> tag to inform the user that JavaScript is required. What (if any) additional step should you take?

Add if (document.images) to verify that the browser supports images. Add if (document.images) to verify that the browser supports images. If you have an X/HTML document containing images, you can access the images through their array numbers using the image object. Note that not all browsers support the image object. Whenever accessing an image object in your JavaScript code, ensure that the user's browser supports the image object by adding an if statement containing the image's array as parameter.

Which of the following is a recommended practice for form validation with JavaScript?

Always test your form validations in several browsers. Recommended practices for form field validation with JavaScript include the following: Always test your form validations in several browsers. Make your messages clear and be concise in your alerts. Do not test multiple fields in one validation. Only use validation when absolutely necessary. Check carefully that your validations do not override each other. If you require something in your form, be sure to test for it in the validation. Make your expectations clear before a user completes a form.

What is an event handler? Name two simple event handlers.

An event handler is a JavaScript mechanism for intercepting an event and associating executable code with that event. Two simple event handlers are onload and onunload.

In JavaScript, what is an expression? Name the six basic JavaScript expressions types.

An expression is a part of a JavaScript statement that is evaluated as a value or assigns a value to a variable. The four JavaScript expression types are assignment, arithmetic, string, logical, conditional and comparison.

In JavaScript, what is an operator? List at least three operators and describe their functions or types.

An operator is a character or characters used in an expression to store or return a value, usually manipulating operands (data) in the process. Examples of operators that can be listed for this question include = (assignment), + (arithmetic or string), && (logical), == (comparison), ++ (unary), and so forth. (A complete list of operators is provided in this lesson.)

Passing arguments to functions

Arguments, or parameters, are values passed into a function from outside the function. These values are then used inside the function and discarded after the function has completed its statements.

he JavaScript object model divides commonly used objects into what groups?

Browser objects, language objects and form field objects The JavaScript object model divides objects into three general groups: browser objects, language objects and form field objects.

What are the two ways in which you can refer to a form element?

By name or by array index number You can refer to a form element in two ways: by its name or by its index number in the form object's elements array. You assign the name using the element tag's name="" attribute. The entered value is information entered into the form field by the user.

Which of the following is true about functions in JavaScript?

Calling a function from within itself will result in an error. Calling a function from within itself will result in an error. You can call a function from one function to another, from a user event, or from the same or a separate <script> block.

Which of the following is true about calling statements in JavaScript?

Calling statements require parentheses, even if the function does not require arguments to be passed. Calling statements require parentheses, even if the function does not require arguments to be passed. A function's statements are processed when the function is called by a calling statement. A function can be called by another function or script block. Calling statements must match the function's signature, which means they must invoke the function by its name and pass the exact amount of arguments the function requires. The curly braces must encompass any statements that are to execute as part of that function. Parentheses () must follow the user-defined function name. These parentheses are used to receive arguments, although a function does not necessarily have to take or use arguments.

Which type of JavaScript expression makes decisions in a script by determining an expression as either true or false, then evaluating the corresponding expression?

Conditional JavaScript uses the following six basic types of expressions: assignment, arithmetic, string, logical, comparison and conditional. A conditional expression makes decisions in a script; the expression (condition) will return either true or false, then evaluate the corresponding expression.

Which of the following is a benefit of client-side form validation?

Conservation of bandwidth Some benefits of client-side validation are conservation of bandwidth, increased end-user satisfaction, and increased validity of form submissions. Client-side validation requires more scripting to accomplish, but is worth the effort. It is not possible to completely validate all form submissions; however, some validation is better than none. Client-side validation is not performed to store data; this action can be taken after the validation is complete and is generally performed on the server side.

Which of the following is true about control structures?

Control structures make desicions based on Boolean values. In programming, statements that make decisions based on Boolean values are referred to as control structures. Statements that cause code to execute repeatedly, or loop, are also control structures. For control structures that use Boolean values, generally a comparison operator is used in the pertinent expression.

Consider the following code: <script type="text/JavaScript"> <!-- var age; function showAge() { getAge(); alert(age); } function getAge() { age = prompt("Please enter your age:","18"); } // --> </script> <body onload="showAge();"> In what order will the functions excecute?

First getAge, then showAge First getAge will execute, then showAge will execute. When a function is called from another function, the focus is passed to the second function. In this example, the function showAge() is called using the onload event handler. Note that the first line of the showAge() function calls the getAge() function. The getAge() function would then execute in its entirety before processing of the showAge() function is completed.

What does the with statement tell your script?

For the body of the statement, any references that follow refer to the same object. If you are going to use several properties and/or methods with a single object, you can use the with statement. The with statement simply says that for the body of the statement, any references that follow refer to the same object. The with statement can save you some coding time. Keep in mind that the with statement should be used with caution. The with statement can be difficult to control because it allows you to use an object (such as a document object) without explicitly stating it each time. It can also be difficult to keep in scope, because the with statement will only be used in the scope where the function is written. If a function inside a with block is defined as a named function instead of anonymous, it can cause problems. An alternative to avoid this is to define a variable.

Historically, the majority of scripting in X/HTML pages has focused on what?

Forms and form elements Perhaps the most common need from a Web developer's perspective is the ability to retrieve and verify data from the user through an X/HTML form. Historically, the majority of scripting in X/HTML pages has focused on forms and form elements. As the capabilities of scripting languages and browsers grow, the primary user interface in Web pages is still the form.

casting

In JavaScript, a technique for variable control in which a variable's value is changed from one data type to another.

global variable

In JavaScript, a variable declared outside of any function, whose value can be accessed from any function or script block on the page.

local variable

In JavaScript, a variable declared within a function, whose value cannot be accessed from any function other than the one in which it was declared.

metacharacter

In programming, a character that has special meaning, or that can represent a variety of other characters. var myRegExp = /\d{3}-?\d{3}-?\d{4}/; document.write The first symbol in the pattern is the \d symbol. This symbol is referred to as a metacharacter and is used to represent any numeral between 0 and 9.

control structure

In programming, a statement that uses a comparison operator to make decisions based on Boolean values, or a statement that causes code to execute repeatedly (i.e., loop).

containership

In programming, the principle that objects are contained within larger objects, and some objects cannot be used or referenced without also referencing the parent (container) object.

regular expression

In scripting/ programming, a mechanism that searches for specified patterns in text.

Consider the following code: var x = 0; while (x < 10){ document.write(x); } How many times will this statement execute?

Infinitely, until the browser is closed This statement will execute an infinite number of times, until the browser is closed. An improperly coded while statement can set up an infinite loop that could cause the browser to wait indefinitely. In this case, the x value of 0 will always be less than 10, so there is no condition to stop the loop. Therefore, be sure to include some statement within the while condition to ensure that at some point the test condition will become false, thus terminating the loop.

Why should the with statement be used with caution?

It can be difficult to control because it allows you to use an object without explicitly stating it each time. If you are going to use several properties and/or methods with a single object, you can use the with statement. The with statement simply says that for the body of the statement, any references that follow refer to the same object. The with statement can save you some coding time. Keep in mind that the with statement should be used with caution. The with statement can be difficult to control because it allows you to use an object (such as a document object) without explicitly stating it each time. It can also be difficult to keep in scope, because the with statement will only be used in the scope where the function is written. If a function inside a with block is defined as a named function instead of anonymous, it can cause problems. An alternative to avoid this is to define a variable.

What is the purpose of the do...while statement?

It executes the code once, then checks to see if the condition is true and continues to execute the code for as long as a condition is true. The do...while statement operates like the while statement (which executes a block of code for as long as a condition is true), with one key difference: The do...while statement does not check the conditional expression until after the first time through the loop, guaranteeing that the code within the curly braces will execute at least once. The if...then statement checks the test condition, then branches to one of two or more processes, depending on the result of the condition. The primary purpose of the for statement is to repeat a group of statements for some particular range of values.

What is the purpose of the prototype function for String objects?

It is used to create your own methods and properties for the String object. The prototype function can be used to create your own methods and properties for the String object. It can add new functions to existing types.

Consider the following code: <html> <head> <script language="JavaScript" type="text/javascript"> function formatMessage() { return "The message of the day is: " + this.toString(); } String.prototype.message = formatMessage; </script> </head> <body> <script language="JavaScript" type="text/javascript"> document.write("Have a great day".message()); </script> </body> </html>

It will display the following text: The message of the day is: Have a great day The code will display the following text: The message of the day is: Have a great day. The function formatMessage is called with the text "Have a great day" which is appended to the text "The message of the day is: "

Consider the following code: var msg = "A Message"; alert("\"" + msg + "\" is " + msg.length + " characters long."); What will this script display?

It will display: "A Message" is 9 characters long. The script will display the following: "A Message" is 9 characters long. There are nine characters in the variable msg because each space is counted as a character when counting the length of a string. Adding the special character \" to the alert message will render the double quotation mark character in the output.

Consider the following code: var msg = "A Message"; alert("The extracted text is: " + msg.substring(3, 6)); What will this script display?

It will display: The extracted text is: ess It will display: The extracted text is: ess. Because strings are indexed from zero instead of one, the character at position 3 is e. The function will then take characters up to but not including the ending index specified, giving us ess.

Consider the following code: var msg = "A Message"; alert("The position of M in \"" + msg + "\" is " + msg.indexOf("M")); What will this script display?

It will display: The position of M in "A Message" is 2 The script will display: The position of M in "A Message" is 2. The letter M is the third character in the string, and because the indexing is zero-based (counting begins at zero instead of one), the index of the M character is 2.

Consider the following code: var myString = "[email protected]" alert(myString.substr(4)); What will this code display?

It will display: somewhere.com The code will display: somwhere.com. When the substr property does not have a second parameter specified, it will take all characters from the position specified to the end of the string.

You created a Web page and saved it on January 1, 2011. You included some JavaScript code that will allow the user to modify X/HTML on the fly. Consider the following code, placed at the bottom of the page: document.write(document.lastModified); What will this code generate when a user loads the page after January 1, 2011?

January 1, 2011 This code will generate January 1, 2011 on the page. The lastModified property can be used to return the date and time at which the document was most recently saved.

Relationship between JavaScript and Java

JavaScript and Java are different languages and have no relationship.

Returning values from functions

JavaScript functions can return values to the calling statement using the return statement. The value to be returned is placed after the return keyword. The value that is returned from a function can be assigned to a variable or it can be used in an expression.

object-based language

JavaScript is an object-based language because it derives functionality from a collection of built-in objects.

Which type of JavaScript expression evaluates to true or false?

JavaScript uses the following six basic types of expressions: assignment, arithmetic, string, logical, comparison and conditional. A logical expression evaluates to true or false.

onload event handler

Message when you hit home or back <!-- onunload event handler calls alert() method --> <body onunload = "alert('Goodbye, ' + userName + '. Hurry back!');">

In JavaScript, what type of methods are also called functions?

Methods that return a value Methods that return a value are also called functions. A function is a named block of code that can be called when needed. In JavaScript, a function can return a value. Functions are fundamental tools in JavaScript. By plugging data into a function, a value will return either to the screen, to a variable, or to another function.

pass by value

Mode that describes when values are passed to a function, and the function's parameters receive a copy of its argument's value.

pass by reference

Mode that describes when values are passed to a function, and the function's parameters receive its argument's actual value.

Name the five data types that can be stored in a variable in JavaScript.

Object, Boolean, number, string and null. An additional type, undefined, occurs when no value is specified; this differs from null, which is actually a value.

Which task is an example of a server-side JavaScript application?

Parsing and disseminating user-submitted information

inline scripting

Placing JavaScript code within an X/HTML tag, rather than between the file's <body> </body> tags.

In JavaScript, what is inline scripting?

Script within an X/HTML tag Inline scripting refers to the placing of JavaScript code within an X/HTML tag, rather than between the file's <body> </body> tags.

What advantage do scripting languages such as JavaScript offer over programming languages such as Java?

Scripting languages offer extended functionality, but are easier and quicker to learn than full programming languages.

Which of the following statements about client-side validation is true?

Some shortcuts exist to bypass validations. Client-side validation can prove very useful but cannot be completely relied upon, because some shortcuts exist to bypass validations. An experienced hacker can get around validations by identifying them (JavaScript is typically visible) and re-engineering their input to bypass the validations. If the information you collect in your forms will go to a database, then you should back up your validations with server-side programming.

What is concatenation?

Synthesis of code to simplify it and reduce duplication. In JavaScript, concatenation is often used to combine text strings for further manipulation.

Which XHTML tag can contain the onload event handler used to execute JavaScript code when a page is loaded?

The <body> tag The onload event handler intercepts the loading of a Web page and allows the programmer to associate executable code with this event. The onload keyword is added to the <body> tag as an attribute. The onload event is implied in JavaScript, meaning that any code that is not included in a function will execute when the page is loaded.

Which of the following objects is a built-in JavaScript object that is not part of the W3C Document Object Model (DOM)?

The Array object The Array object is a built-in JavaScript object. Some objects, such as the window, document and form objects, represent elements of the Document Object Model (DOM). The DOM is a World Wide Web Consortium (W3C) programming specification intended to give developers access to all elements within an X/HTML page or XML document. Other objects, such as Array and String, represent built-in JavaScript objects.

In general, which JavaScript object can you use to manipulate and test the values in form elements before they are sent to CGI scripts and other processes?

The String object In general, you can use the String object to manipulate and test the values in form elements before they are sent to CGI scripts and other processes. Using the Date object, you can customize a Web page on the fly, and using the Math object furthers your ability to create sophisticated applications. Regular expressions (the RegExp object) provide powerful pattern-matching capabilities for JavaScript programs.

user agent

The W3C term for any application, such as a Web browser or help engine, that renders X/HTML for display to users

Consider the following code: var msg = "A Messy Memo"; alert(msg.lastIndexOf("M")); What will be displayed in the alert box?

The alert will display: 8 The alert will display: 8. The lastIndexOf property will look for the first occurrence of the search string starting from the end of the query string. That is, it returns the position of the last-found occurrence of the specified value in the query string. The string is searched backward, but the index position returned is the character's position counted from left to right (from 0). Thus the first M encountered starting from the end of the string and working backward is in position 8.

You have opened a window to http://www.myweb.com/faq/answers.htm?protocol=email. Consider the following alert: alert(location.protocol); What will this alert display if added to the code of your document?

The alert will display: http: The alert will display http:. The properties of the location object relate to the various pieces of information that form a complete URL. In many applications, accessing this information is extremely important. These properties allow the developer easy access to this data without having to perform rather complex string manipulation. The elements of the URL are identified as follows: protocol://hostname:port/pathname/search#hash

Which of the following statements is true?

The alert(), prompt() and confirm() methods are all methods of the window object.

Which simple JavaScript methods can you use to communicate with users?

The alert(), prompt(), confirm() and document.write() methods.

You are developing a Web application that requires features available only in the latest version of certain browsers. Which propertie(s) of the navigator object must you include to verify that the user is employing one of the correct browsers?

The appName and appVersion properties You must include the appName and appVersion properties. The navigator object reflects information about the browser being used. This object can determine the brand and version of the browser in use, and even identify the user's operating system. The appName property returns a string value containing the name of the client. The appVersion property returns a string value containing the version information for the client. The appCodeName property returns a string value containing the code name for the client (for example, it returns the default Mozilla for the Mozilla browsers and also for Internet Explorer and Google Chrome). The userAgent property returns a string value containing the complete value of the user agent header sent in the HTTP request

uppose you create an array as follows: var myArray = new Array(5); Then you assign the following value: myArray[50] = "Too high"; What will be the result?

The array myArray will now have 51 elements. The array myArray will now have 51 elements. If the position created has an index of 50, then the array will have 51 elements instead of 50 because it is zero-based. The size of the array is dynamically adjusted to have as many elements as the highest subscript used.

Which type of statement provides a way to exit a loop that would otherwise continue to execute?

The break statement A way to exit a loop that would otherwise continue to execute is to use the break statement. Usually, you will find the break keyword inside an if clause. If a certain condition is reached, the program will break out of the loop. If not, the loop will continue. You can use the break statement within the for, while and do...while loops, as well as with the switch statement.

Which JavaScript object provides a basic push-button interface and relies on scripting for its functionality, rather than operating in a predefined manner?

The button object The button object provides a basic push-button type of user interface element on an X/HTML page. Whereas Submit or Reset buttons operate in a predefined manner, the button object depends on scripting for its functionality.

Which of the following is the main property associated with the JavaScript checkbox object, and returns a Boolean value?

The checked property The main property associated with a checkbox object is checked. The checked property returns a Boolean value of true or false. If the box is checked, the return value is true. If the box is not checked, the checked property returns the Boolean value of false. The defaultchecked property returns a Boolean value indicating true if the checked attribute was used in the <input> tag for the checkbox object. The form property returns a reference to the form object containing the element. The name property specifies or returns a string value of the name of the object as determined by the name attribute.

Marcos is trying to validate a user's access permissions. He wants to give admin permission only to the username "Admin." He includes the following code in his script, but he gets an error: adminPermission = (UserName="Admin") true: false; What is the problem with his code?

The conditional operator requires a logical or comparison expression, but an assignment expression is used. The == and === operators are comparison operators and should be used in this code instead of the = operator. The = operator is an assignment operator.

Which method is used to ask the user a true-or-false type of question?

The confirm() method Often in programming, you will want to ask the user a simple yes-or-no (true-or-false) type of question. You can use the confirm() method to do this with a message box that provides both OK and Cancel buttons. It is similar to the alert() method with one significant exception: The confirm() method returns a value of either true or false, whereas the alert() method has no return value. `

Which JavaScript statement is used to force the flow of control back to the top of a loop?

The continue statement The continue statement is used to force the flow of control back to the top of a loop. You can think of continue as a "skip" or bypass command. When execution hits a continue statement, all statements between it and the end of the loop block are skipped, and execution returns to the top of the loop. The test condition for the loop is then evaluated to determine whether the loop should execute again. The continue statement can be used only within a for or a while loop.

A new Date object has been assigned to a variable using the following statement: var myDate = new Date(); What will be the initial value of the variable?

The current date and time This variable is initially set to the current date and time. Calling new Date() without parameters will set the variable to today's date and time.

How does the do...while statement differ from the while statement?

The do...while statement guarantees that the code within the curly braces will execute at least once, whereas the do statement does not. The do...while statement operates like the while statement (which executes a block of code for as long as a condition is true), with one key difference: The do...while statement does not check the conditional expression until after the first time through the loop, guaranteeing that the code within the curly braces will execute at least once. The if...then statement checks the test condition, then branches to one of two or more processes, depending on the result of the condition. The primary purpose of the for statement is to repeat a group of statements for some particular range of values

Which of the following is the container of the form object?

The document object In JavaScript, the document object is the container of the form object. Containership relates to the principle that some objects cannot be used or referenced without a reference to the parent (container) object. For example, you cannot reference a form element in JavaScript without referring both to the form object and the document object that contains the form object.

Which JavaScript object is a combination of the content and interface elements that constitute the current Web page?

The document object The document object is a combination of the content and interface elements that constitute a Web page. The document object provides the properties and methods to work with many aspects of the current document, including text, anchors, forms, links, page title, current location and URL, and the current background and foreground colors. The document object is subordinate to the window object in the JavaScript hierarchy.

Consider the following code: with (document) { open(); } The open() method of which object is being invoked?

The document object This code invokes the open() method of the document object. If you are going to use several properties and/or methods with a single object, you can use the with statement. The with statement simply says that for the body of the statement, any references that follow refer to the same object.

Which method of the text and textarea objects occurs when the user's cursor moves over the object without clicking?

The focus() method The focus() method of the text and textarea objects occurs when the cursor moves over the object, giving it focus. The blur() method occurs when the cursor moves off of the object, causing it to lose focus or blur. The select() method highlights (selects) the text in the object by clicking or clicking and dragging. The onchange event handler specifies the JavaScript code to execute when the object loses focus after a user enters text.

Which JavaScript statement should you use to repeat a group of statements for some particular range of values?

The for statement The primary purpose of the for statement is to repeat a group of statements for some particular range of values. The continue statement is used to force the flow of control back to the top of a loop. The if...else statement provides a way to handle the possibility of a false value (i.e., an incorrect answer from a user) being returned by the test condition. The do...while statement operates like the while statement (which executes a block of code for as long as a condition is true), with one key difference: The do...while statement does not check the conditional expression until after the first time through the loop, guaranteeing that the code within the curly braces will execute at least once.

Where is the best place in an XHTML document to place a function?

The head of the document Define all your functions in the <head> element of your X/HTML page. That way, when the page is loaded into the browser, the functions will load before any user event can occur that might call the function.

Which JavaScript object allows you access to previously visited Web page URLs?

The history object The history object allows you access to previously visited Web page URLs. You use the same information used by the history object when you click the Back or Forward buttons on your browser. The browser maintains a list of recently visited Web page URLs, and you can display these pages by clicking the browser buttons. If you want to give the same type of functionality to your own pages, you can add similar buttons or links that allow the user to move backward or forward through the stored history of your Web page. To access the previous pages visited, you can use the history object with the back() and forward() methods.

Which JavaScript statement should you use to test for a single condition and branch to a process?

The if statement The if and if...else statements provide the ability to branch to one of two or more processes, depending on the result of some test condition that you have scripted. The if statement is used to test for a single condition. The if...else statement allows you to test for multiple conditions, in order to handle the possibility of a false value (i.e., an incorrect answer from a user) being returned by the test condition. The while statement is used to execute a block of code for as long as (while) a certain test condition is true. The primary purpose of the for statement is to repeat a group of statements for some particular range of values.

Consider the following code: for (var x = 0; x < 26; x+=5) { document.write(x + " "); if (x == 10) break; } What will be the last number printed to the document?

The last number will be: 10 The last number printed to the document will be 10. A way to exit a loop that would otherwise continue to execute is to use the break statement. Usually, you will find the break keyword inside an if clause. If a certain condition is reached, the program will break out of the loop. If not, the loop will continue. You can use the break statement within the for, while and do...while loops, as well as with the switch statement.

Which JavaScript object allows you to specify URLs in a script?

The location object The location object allows you to specify URLs in a script. Thus you can create buttons instead of text or graphic links to send users to different targets. You can also tie the change of location to some other portion of script. The key property of the location object you will frequently use is the href property, which specifies or returns the hypertext reference for the current or desired URL. The location object is subordinate to the window object in the JavaScript hierarchy.

Which JavaScript object provides essential information if you must code your script for use in different browsers?

The navigator object The navigator object provides essential information if you must code your script for use in different browsers. The navigator object reflects information about the browser being used. This object can determine the brand and version of the browser in use, and even identify the user's operating system.

What event can trigger JavaScript functions as an X/HTML page loads?

The onload event

Consider the following JavaScript statement: document.write(8 / 4 * 2 + 2 / 2); What is the output of this statement?

The output is: 5 The output of this statement is 5. The division operator (/) takes precedence over the addition operator (+). The division operator and the multiplication operator (*) share the same precedence, thus they are read left to right. The statement is evaluated as (8 / 4) = 2 * 2 =4 + 1 (result of 2 / 2), which equals 5. In programming, operator precedence determines which expressions will be evaluated before others.

Consider the following code: <script type="text/javascript"> var myArray = new Array("Abbott", "Costello"); var actors = myArray.join(" and "); document.write(actors); </script> What will be the output of this script?

The output will be: Abbott and Costello The output will be: Abbott and Costello . The join function will concatenate all the items in the array using the specified string as a separator. The separator is not repeated after the last element.

Consider the following JavaScript code: var counter = 0; document.write(counter++); document.write(counter++); document.write(counter++); What would be the result of this code when run in the browser?

The result is: 012 The result of this code would be 012. The increment operator (++) increases the value of the supplied operand by one. If the increment operator is placed before the operand, then the operation occurs immediately. If the increment operator is placed after the operand, then the change in the operand's value is not apparent until the next time the operand is accessed in the program. In this example, the script would write 0 as the first value because the increment operator is placed after the operand, so the incremented value does not appear until the second time the variable counter is accessed in the program.

Consider the following JavaScript expression: parseInt("1.5y"); What is the result of this expression?

The result is: 1 The result of this expression is 1. The parseInt() method converts a string into its integer equivalent, and does not include letters. In order to display the floating-point decimal portion (1.5), you would need to use the parseFloat() method.

Consider the following JavaScript code: var counter = 0; document.write(++counter); document.write(++counter); document.write(counter); What would be the result of this code when run in the browser?

The result is: 122 The result of this code would be 122. The increment operator (++) increases the value of the supplied operand by one. If the increment operator is placed before the operand, then the operation occurs immediately. If the increment operator is placed after the operand, then the change in the operand's value is not apparent until the next time the operand is accessed in the program. In this example, the script would write 1 as the first value because the increment operator is placed before the operand, causing the operation to occur immediately.

Consider the following expression: 30 < 50; What is the result of this expression?

The result is: true The result of this expression is true. The characters <, >, =, and their combinations are logical operators. Logical expressions evaluate to Boolean values (true or false). Because 30 is less than 50, this expression evaluates to the Boolean value of true.

Consider the following JavaScript code: var aString = "Some text."; aString.bold(); document.write(aString); What is wrong with this code?

The result of the bold function is not assigned to anything. The problem with this code is that the result of the bold function is not assigned to anything. After performing the bold function, the value needs to be assigned to a variable. It can be same variable or a different one. But by not assigning the value, the result of the action is lost.

Consider the following JavaScript statements: var myValue = 20; myValue += 20; myValue = myValue * 10; myValue += "20"; myValue = "New value"; For each of these statements, what does the myValue variable evaluate to after each statement executes in JavaScript?

The result would appear as follows: 20 40 400 40020 New value

Consider the following JavaScript code: var fabfour = "John, Paul, George, Ringo"; var myRegExp = /aul/; document.write(fabfour.search(myRegExp)); What will this script display when run in the browser?

The script will display: 7 The script will display: 7. The search routine will return the index position of the text that matches the regular expression.

What procedure does your script perform in order to determine which options were chosen by the user in a multiple-selection list box?

The script will loop through each option, checking the value of the selected property. The script will loop through each option in the list, checking the value of the selected property to determine which ones are set to true, and those are the options that were chosen by the user. There is no array that maintains the list of selected options in a multiple-selection list; one must query the selected property on each option in the list to see if it is true.

What procedure does your script perform in order to determine which radio button was chosen by the user?

The script will loop through the radio button group, querying the checked property for each element. The radio buttons are stored in an array in the form object. This array does not have any properties indicating which element was checked. The script must loop through the list, inspecting each radio button object's checked property to determine which one is set to true, and this is the one that was chosen by the user.

Which JavaScript object allows the user to choose one or more items from a list box?

The select object The JavaScript select object allows the user to choose one or more items from a list box. The radio object allows the user to choose an option from a set of mutually exclusive option buttons. The checkbox object allows the user to submit a yes/no or true/false option, and choose more than one option from a set of options. The textarea object is for a scrolling text box used for data entry.

You are developing an application for enrollment in a grade school. You have included a variable for the grade level, and you want to assign a default value based on the age of the applicant. Which control structure will allow you to accomplish this in the most efficient way?

The switch statement The switch statement compares a value against other values, searching for a match. If a match is found, then the code associated with the match will execute. The break statement is then used to exit the switch block of code. Essentially, the switch statement functions the same as multiple else if clauses within an if statement. However, switch is more readable and allows you to specify a default set of statements to execute if no match is found.

Which JavaScript object allows input of a single line of alphanumeric values and provides programmatic access to these user-entered values?

The text object The JavaScript text object allows input of a single line of alphanumeric values and provides programmatic access to these user-entered values. The textarea object is for a scrolling text box used for data entry. The select object allows the user to choose one or more items from a list box. The submit object sends the contents of a form to a server.

Consider the following code: function counter(x) { x++ } var myVar = 0; counter(myVar); What is the value of myVar after execution?

The value is: 0 The value of myVar after execution is 0. If a variable is passed to a function, changing the value of the argument within the function does not change the value of the original variable outside the function.

Consider the following JavaScript code: function concatenate(txt1, txt2) { txt1 += " "; var myText; return txt1 + txt2; } var myText = concatenate("Hello","World"); What is the value of myText after execution

The value is: Hello World The value of myText after execution is Hello World. JavaScript functions can return values to the calling statement using the return statement. The value to be returned is placed after the return keyword. The value that is returned from a function can be assigned to a variable or it can be used in an expression.

Which property of the button object can you use to specify a string of the text that will be displayed on the button?

The value property The button object's value property specifies or returns a string value of the text displayed on the button as determined by the value attribute. The form property returns a reference to the form object containing the element. The name property specifies or returns a string value of the name of the object as determined by the name attribute. The button object's main method is click(), and its main event handler is onclick.

After a user has entered information into a text field, which property is used to retrieve the information?

The value property The value property of the text object returns a string value of the current text box contents when the form is submitted, thus it can retrieve any data entered by the user. The name property specifies or returns a string value of the name of the object as specified in the <input> tag with the name attribute. The form property returns a reference to the form object containing the element. The defaultValue property returns a string value indicating the value as specified in the <input> tag with the value attribute.

Consider the following code: var x = 100; while (x > 5) { x--; } What will be the value of x after execution?

The value will be: 5 The value of x after execution of this code will be 5. The condition under which the while statement executes is (x > 5) so the last time the loop will execute is when x has a value of 6. Because the code inside the while statement will execute, x will be decremented by 1 one more time, making its value 5.

Consider the following code: var userName = prompt("Enter User Name",""); var accessLevel = "None"; if (userName == "Admin") { accessLevel = "Full"; } else { accessLevel="Limited" } What will be the value of the accessLevel variable after execution if the user enters John as the user name?

The value will be: Limited The value of accessLevel will be: Limited. Because the condition of the if statement will return false, the content of the else block will be executed.

Consider the following code: var myString = "Have a great day!"; var extracted = myString.charAt(myString.length - 1); What will be assigned to the variable extracted in this code?

The variable extracted will be assigned: ! The variable extracted will be assigned: !. The position corresponding to string.length - 1 is the last character in the string because strings are indexed from zero, not one.

What is the default object in JavaScript?

The window object The window object is the highest-level object in the JavaScript object hierarchy, and is also the default object. The window object represents the frame of the browser and the mechanisms associated with it, such as scroll bars, navigation bars, menu bars and so forth.

Which JavaScript object represents the frame of the browser and the mechanisms associated with it?

The window object The window object represents the frame of the browser and the mechanisms associated with it, such as scroll bars, navigation bars, menu bars and so forth. The window object is the highest-level object in the JavaScript object hierarchy, and is also the default object.

The alert(), prompt() and confirm() methods are methods of which object?

The window object.

Which of the following allows you to use several properties and/or methods with a single object?

The with statement If you are going to use several properties and/or methods with a single object, you can use the with statement. The with statement simply says that for the body of the statement, any references that follow refer to the same object. The syntax for using with is as follows: with (objectname) { //statement(s) referencing objectname The with statement can save you some coding time.

The === and !== operators

These operators denote strict comparison, in which not only the value but also the data type of both operands must be equal (===) or not equal (!==). In non-strict comparison (==), JavaScript will attempt to convert the operands of different types in an expression to the same type, but same data type is not required for the expression to evaluate to true. In strict comparison, same data type (or different data type for !==) is required for the expression to evaluate to true.

To JavaScript, what is the difference between a text object and a textarea object?

They are very similar -- they use the same properties, methods and event handlers. To JavaScript, the text and textarea objects are very similar. The same properties, methods and event handlers are available to both. To the user, of course, they are very different. A text object displays a single line of text, whereas a textarea object can display multiple, scrolling lines of text. Note that a textarea box is created with a <textarea> tag instead of an <input> tag, as is a text box.

How many arguments does the window.open() method require?

Three arguments The window.open() method requires a minimum of three arguments. You open a new window by using the window object's open() method. You can launch a new window displaying an existing Web page, or you can launch an empty window and then populate it on the fly (i.e., dynamically) with content defined by your scripts. The generic syntax to open a new window using the open() method is as follows: open("URL","WindowName","Feature List") Notice that "Feature List" is one argmuent with one or multiple values.

What is the purpose of the JavaScript form object?

To access all properties of the form and elements that compose the form The form object is used to access all properties of the form, most importantly the elements that compose the form. The JavaScript form object represents an X/HTML form in JavaScript. Each form on a page is represented by a separate instance of the form object. All form objects for the page are contained within the forms array and can be accessed as forms[0], forms[1], etc. The X/HTML form elements create the form field elements that appear to users on screen.

What is the purpose of the switch statement?

To compare a value against other values, searching for a match The switch statement compares a value against other values, searching for a match. If a match is found, then the code associated with the match will execute. The break statement is then used to exit the switch block of code. Essentially, the switch statement functions the same as multiple else if clauses within an if statement. However, switch is more readable and allows you to specify a default set of statements to execute if no match is found. The continue statement is used to force the flow of control back to the top of a loop. The break statement provides a way to exit a loop that would otherwise continue to execute. The primary purpose of the for statement is to repeat a group of statements for some particular range of values.

<noscript> tag

To display alternate content for browsers that do not support JavaScript

Which of the following is a good reason to use external .js files?

To facilitate frequent revisions

What is the primary purpose of the for statement?

To repeat a group of statements for some particular range of values The primary purpose of the for statement is to repeat a group of statements for some particular range of values. The format of a for statement is as follows: for (x; y; z) { //one or more statements } The switch statement compares a value against other values, searching for a match. The continue statement is used to force the flow of control back to the top of a loop. The break statement provides a way to exit a loop that would otherwise continue to execute.

What is the purpose of the clearTimeout() function?

To stop a timer that was set with the setTimeout() function When declaring a setTimeout, you should assign the function to a variable so that later, the clearTimeout function can be called to stop the timer. Following is an example of the code: var t=setTimeout("alert('I am displayed after 2 seconds!')",2000); clearTimeout(t);

Consider the following code: var season = 5; var seasonName = "Summer"; switch (season) { case(1): seasonName = "Winter"; break; case(2): seasonName = "Spring"; break; case(3): seasonName = "Summer"; break; case(4): seasonName = "Fall"; break; default: seasonName = "Unknown"; } What is the value of seasonName after execution?

Unknown The value of seasonName after execution will be Unknown because the variable value supplied for season (5) does not match any of the cases given, and thus the default value is the result. The switch statement compares a value against other values, searching for a match. If a match is found, then the code associated with the match will execute. The break statement is then used to exit the switch block of code. Essentially, the switch statement functions the same as multiple else if clauses within an if statement. However, switch is more readable and allows you to specify a default set of statements to execute if no match is found.

Which version of JavaScript introduced the ability to use a dollar sign ($) at the beginning of a variable name?

Version 1.5 The JavaScript 1.5 specification began allowing variable names to begin with the dollar sign ($). Remember that the user must be utilizing a user agent that supports JavaScript 1.5 or later.

Generally speaking, when is the JavaScript form object available to access in an X/HTML page?

When <form> tags are present in the X/HTML document The form object represents an X/HTML form in JavaScript. This object is available when <form> tags are present in the X/HTML document.

You want to create some client-side validations to ensure that your end users answer each of the required questions in your form. For a text field that requires the user to enter the number of years he or she has worked at a past job, you can validate that the user entered an answer by creating a script that detects what?

Whether the field holds a null value after submission You can create client-side form field validations to ensure that your end users answer required questions in your form by creating scripts that test each required form element for various input. For a text field that will require a short entry that may be as little as one character, you can test to detect whether the field holds no value (or a null value) after submission. For a text field that requires a name, you can test to detect a minimum number of characters. For a text field that requires an e-mail address, you can test to detect whether the @ symbol is used. For a select list or radio button, you can test to detect whether the field value was changed from the default. It is not possible to verify whether a user submits truthful information, only that they submit any information or information in a specified format.

Is it possible to scroll a document using JavaScript?

Yes, scrolling is possible using window.scrollTo(). Yes, scrolling is possible in JavaScript using window.scrollTo(). The scrollTo() method scrolls the document in a window to the specified position on the x-axis and y-axis. The scrollBy() method scrolls the document in a window by the specified x and y offsets along the x-axis and y-axis.

substring()

You specify the beginning index position and the ending index position. Consider the following example: var myString = "This is text."; var mySubStr = myString.substr(1, 3); var mySubString = myString.substring(1, 3) document.write(mySubStr + " " + mySubString); This code would output: his hi

substr()

You specify the beginning index position and the number of characters to extract starting at that position. Consider the following example: var myString = "This is text."; var mySubStr = myString.substr(1, 3); var mySubString = myString.substring(1, 3) document.write(mySubStr + " " + mySubString); This code would output: his hi

Which of the following examples is a valid variable name in JavaScript?

_lastName In JavaScript, valid variable name is _lastName. When naming variables you must follow certain rules: The first character of the variable must be a letter or the underscore ( _ ) character. No other initial characters are allowed (except for $ in some versions). Subsequent characters can be letters, numbers and/or underscore characters, but symbols (other than $) are not allowed.

JavaScript reserved words

abstract boolean byte break case char comment default delete double else FALSE final float goto implements instanceOf int interface long native null package private protected public short static synchronized throws transient TRUE

When a user submits a form by clicking a button, which property of the form object specifies a URL to which the form data will be sent for processing?

action The action property of the form object specifies a string value for the URL to which the form data is submitted. The target property specifies or returns a string value containing the name of the window to which responses to form submissions are directed. The method property specifies or returns a string value containing the submission method of form data to a server. The name property specifies or returns the name of the form as defined in the <form> tag.

Which of the following is an example of a user-defined JavaScript function?

addSpace() Of the choices given, an example of a user-defined JavaScript function is addSpace(). The other three are all built-in functions, which are already defined by the JavaScript language.

An interface you are developing will display an array in a list format. You want to allow the user to flip the list, making the first item last and the last item first, reversing the order of all items. Which statement will achieve this?

arrayList.reverse(); The correct statement is arrayList.reverse();. Arrays have a method that can be applied to them to flip or reverse the order. The reverse method does not take any parameters. It will change the array so that the first entry is now last, second entry is second to last, the last entry is first and so forth.

Which event occurs when input focus is removed from a form element (e.g., when a user clicks the mouse button outside of a particular field)?

blur The blur event occurs when input focus is removed from a form element (e.g., when a user clicks the mouse button outside of a particular field). The focus event occurs when a user gives input or focus to a form element. The click event occurs when the user clicks on a link or form element. The change event occurs when a user changes the value of a form field.

JavaScript keywords

break condition const continue delete do do...while export for for...in finally function if if...else import in instanceOf label let new return switch this throw try...catch typeof var void while with yield

The JavaScript radio object allows users to:

choose at most a single response from a list. The radio object allows users to select an option from among two or more mutually exclusive options. This means that no more than one item can be selected from the group. Users can also select no item at all, although if the group has a default selection then that selection will be recorded as the user's choice if the user does not change it. Radio buttons work well for yes-or-no-type questions, where you want users to respond yes or no, but not both.

What is the main method used by the JavaScript button object?

click() The button object provides a basic push-button type of user interface element on an X/HTML page. Whereas Submit or Reset buttons operate in a predefined manner, the button object depends on scripting for its functionality. Its main method is click(), and its main event handler is onclick. The submit() and reset() methods are used by the form object. The select() method is used by the select object.

parseFloat()

converts a string to its floating-point decimal equivalent

parseInt()

converts a string to its integer equivalent

The JavaScript Math object can be used to:

create advanced mathematical calculations using its properties and methods. The JavaScript Math object contains static properties and methods that give access to advanced mathematical calculations and also holds various constants that are useful in scientific calculations.

Which property of the radio object is used to determine whether a radio button was selected in the X/HTML page's script?

defaultChecked The defaultChecked property returns a Boolean value indicating true if the checked attribute was used in the <input> tag for that radio object. The checked property specifies or returns a Boolean value indicating true if the button is selected or false if the button is not selected. The value property specifies or returns a string value determined by the value attribute. The name property returns a string value of the name of this object as determined by the name attribute.

Consider the following code: <form name="form1"> <input type="checkbox" name="choose" /> </form> How would you refer to the checked attribute of the <input> element in this statement?

document.form1.choose.checked; Of the choices given, the correct reference is document.form1.choose.checked;. One way to refer to an element on the page contained in a form is: document.formname.elementname.attribute. The other way would be to refer to the array of forms or elements, which are zero-based, but these examples started counting form1 at [1] instead of correctly at [0].

Consider the following XHTML fragment: <form name="myForm"> <input type="checkbox" name="myCheckbox" />Click </form> Given this code, what is the correct way to determine whether the check box is checked?

document.myForm.myCheckbox.checked The correct code is document.myForm.myCheckbox.checked. This code properly references the form and check box using the name, and it uses the checked property to retrieve the current state of the check box.

Consider the following variable: var email = [email protected] How can you extract the username portion of the e-mail address in this variable?

email.substring(0, email.indexOf("@")); The correct code is email.substring(0, email.indexOf("@"));. The substring property will grab the characters starting with the first one (in index position 0) up to the character before the @ sign, which is located using the indexOf property. The substring property takes only up to the character immediately before the index position specified by the second parameter, not including that character.

You need to reformat text that the user has entered in italics and lowercase. Which of the following will accomplish this?

enteredString = enteredString.italics().toLowerCase(); The correct code is enteredString = enteredString.italics().toLowerCase();.This choice is the only one where the entered string has both actions applied to it and is then saved back to the variable.

The elements on a form need to be initialized with dates for the next week, starting from today. Only the <input> tags of type text need to be initialized. Consider the following XHTML code: <head> <script type="text/javascript"> function FillDate() { var d = new Date(); // insert loop here } </script> </head> <body> <form name="calendarForm"> <input type="text" name="date1"></input><br/> <input type="text" name="date2"></input><br/> <input type="text" name="date3"></input><br/> <input type="text" name="date4"></input><br/> <input type="text" name="date5"></input><br/> <input type="text" name="date6"></input><br/> <input type="text" name="date7"></input><br/> <input type="button" name="fillDates" onclick="FillDate()" value="Fill Days"></input> </form> </body> Given the code, which loop will accomplish this?

for (var i = 0; i < document.calendarForm.length; i++) { if (document.calendarForm.elements[i].type == "text") { d.setDate(d.getDate() + 1); document.calendarForm.elements[i].value = d.toDateString(); } } The correct code is: for (var i = 0; i < document.calendarForm.length; i++) { if (document.calendarForm.elements[i].type == "text") { d.setDate(d.getDate() + 1); document.calendarForm.elements[i].value = d.toDateString(); } } This answer uses the correct way to get the number of elements in the form via the length property. To determine the element type, it uses the type attribute. The next date is correctly calculated by adding one to the day number obtained with getDate and then setDate is used to get the date element. Finally, the new date is assigned to the value property.

Which code snippet demonstrates the correct syntax for a user-defined JavaScript function?

function my_function() { alert("test function"); } The correct answer is: function my_function() { alert("test function"); } The generic syntax for a JavaScript user-defined function is as follows: function functionName(argument1, argument2, ...) { //statement(s) here }

Consider the following code: for (x; y; z) { //one or more statements } What does x represent in this code?

he loop counter variable The primary purpose of the for statement is to repeat a group of statements for some particular range of values. The format of a for statement is as follows: for (x; y; z) { //one or more statements } In this example, x is the loop counter variable initialization expression, y is the condition under which the loop will repeat, and z is the expression that increments or decrements the loop counter.

Which line of code will redirect the browser user to the page she was previously viewing?

history.back(); The browser maintains a list of recently visited Web page URLs. You can display these pages by clicking the browser buttons. If you want to give the same type of functionality to your own page, you can add similar buttons or links that allow the user to move backward or forward through the stored history of your Web page. To access the previous page in the history list, you can use the JavaScript history object with the back() method.The forward() method sends the user to the subsequent page in the history list. The go(x) method sends the user either back x number of pages (if x is a negative integer, or forward x number of pages (if x is a positive integer) or to a specified URL (if x is a string matching a URL).

if statement

if (Boolean expression) { //statements to execute } In a simple if statement for which no other test condition exists, the general syntax is as follows: if (expression) { //statements to execute if expression is true } Note that the expression (the test condition) is enclosed in parentheses. A set of curly braces encloses a block of a single or multiple statements. These statements will execute only if the expression returns the Boolean value of true. Nothing will happen if the Boolean expression returns a false value.

Which of the following code segments correctly uses JavaScript to preload images for an X/HTML page?

if (document.images) { var pic1, pic2; pic1 = new Image(); pic1.src = "images/pic1.gif"; pic2 = new Image(); pic2.src = "images/pic2.gif"; } To preload images, you create new instances of the image object in the <head> section of the document. You then assign a source for each image using the src property. The construction of a new image object forces the browser to locate and preload that image into the browser's cache. Remember that the image object and the Image() constructor, like all JavaScript, are case-sensitive. The following example demonstrates the entire preloading procedure: <script type="text/javascript"><!-- if (document.images) { var image1, image2; image1 = new Image(); image1.src = "images/image1.gif"; image2 = new Image();<br image2.src = "images/image2.gif"; } //--> </script> The variables image1 and image2 now contain references to preloaded images available for dynamic image swapping as needed.

Which of the following examples demonstrates correct syntax for a JavaScript if...else if...else statement?

if (myCondition == true) { //statements to execute } else if (anotherCondition == true) { //statements to execute } else { //default statements to execute } The correct syntax is as follows: if (myCondition == true) { //statements to execute } else if (anotherCondition == true) { //statements to execute } else { //default statements to execute } The if...else statement provides a way to handle the possibility of a false value (i.e., an incorrect answer from a user) being returned by the test condition. Note that the else keyword is placed after the closing curly brace for the initial block of code associated with the test condition. The else block of code is enclosed in its own set of curly braces and will execute only if the test condition returns the Boolean value of false.

Which code will display an alert if the variable timerMinutes has a value 10?

if (timerMinutes == 10) alert("Time Expired!"); The correct code is: if (timerMinutes == 10) alert("Time Expired!");. In a simple if statement for which no other test condition exists, the syntax is as follows: if (expression) { //statements to execute if expression is true } Note that the expression (the test condition) is enclosed in parentheses. A set of curly braces encloses a block of a single or multiple statements. These statements will execute only if the expression returns the Boolean value of true. Nothing will happen if the Boolean expression returns a false value. If the code associated with a test condition consists of just one line, you can omit the curly braces. There should be no quotation marks arounf the variable name (timerMinutes).

while statement

is used to execute a block of code for as long as (while) a certain test condition is true. When program execution reaches the while statement, the test condition is evaluated. If the expression returns the Boolean value of true, the statements encompassed within the curly braces are executed. Then, program flow returns to the beginning of the while statement, where the test condition is re-evaluated. The code block will repeat itself, or loop, for as long as the expression returns the value of true. The while loop is especially useful when you are not sure how many times the loop will need to execute. The while statement is used to execute a block of code for as long as (while) a certain test condition is true. The general syntax is as follows: while (expression) { //one or more statements to execute } When program execution reaches the while statement, the test condition is evaluated. If the expression returns the Boolean value of true, the statements encompassed within the curly braces are executed. Then, program flow returns to the beginning of the while statement, where the test condition is re-evaluated. The code block will repeat itself, or loop, for as long as the expression returns the value of true.

In JavaScript, the String, Math, Array, Date and RegExp objects are called:

language objects. In JavaScript, the String, Math, Array, Date and RegExp objects are called language objects. They are not part of the JavaScript containment hierarchy (illustrated in a previous lesson), but are nevertheless part of the JavaScript language.

Consider the following code: var msg = "Super Sharp Swords"; Which statement will correctly find the second S in this string?

lastIndexOf("S", 7); The correct statement is: lastIndexOf("S", 7);. The lastIndexOf property returns the position of the last-found occurrence of the first specified parameter (S) in the query string. The second parameter (7) indicates the position in the string from which the search is to begin looking, then it works its way backward from there toward the beginning of the string. Starting at position 7, the first S encountered is the second S in the string.

What is the one property associated with the history object?

length The history object has only one property associated with it, and three methods. The length property returns an integer value representing the number of links currently referenced by the history object. The three methods are back(), forward() and go(x), which send the user to the appropriate page as specified. Note that no events are associated with the history object.

<script type="text/javascript" src="myJavaScriptCode.js">

link an external JavaScript file to an X/HTML doc

Which event occurs when a Web page is launched in the browser?

load The load event occurs when a Web page is launched, or loaded, in the browser. The unload event occurs when the user leaves or closes (unloads) the page. The focus event occurs when a user gives input or focus to a form element. The change event occurs when a user changes the value of a form field

Consider the following script, where msg is a div defined on the page: var str = "A bolded message"; var m = document.getElementById("msg"); Which statement will output the string str formatted in bold?

m.innerHTML = str.bold(); The statement m.innerHTML = str.bold(); correctly applies the bold function to the string and then assigns the output to the variable that will modify the div.

Which attribute is used to allow the user to choose more than one choice from a select object?

multiple To create a multiple-selection list box, you simply add the multiple attribute to the X/HTML <select> tag when creating the select list

You need to create a comma-delimited list from an array of values. Which function will accomplish this?

myArray.join(","); The correct function is myArray.join(",");. The join function will concatenate all the items in the array using the specified string as a separator.

Which statement will reorder and display the array myArray in alphabetical order?

myArray.sort(); The correct statement is myArray.sort();.The sort method will reorder an array into alphabetical order. The original array is changed to store the reordered items.

Consider the following code from an XHTML document: <script type="text/javascript"> function testname() { var fabfour = "John, Paul, George, Ringo"; var input = document.getElementById("nameinput").value; var myRegExp = new RegExp(input); var out = document.getElementById("testoutput"); if( ) { out.innerHTML = "You found him"; } else { out.innerHTML = "Try again"; } } </script> <input id="nameinput"></input> <input type="button" onclick="testname()" value="Check Name"></input><br/> <span id="testoutput"></span> Which of the following statements will allow the if statement in this code to check the input?

myRegExp.test(fabfour) == true The correct statement is myRegExp.test(fabfour) == true. The test() function is the only one that returns a true or false answer from this script.

Consider the following string: var myString = "five four two"; Which statement will extract the characters fou from this string?

myString.substr(6,3); The correct code is: myString.substr(6,3);. This substr property will extract three characters starting at position 6, resulting in fou. The substring property would extract the characters beginning at position 6 and ending at 8. The charAt property will extract only one character from the position specified, so this example does not use correct syntax for that property.

Your users want to see a list of names sorted alphabetically but backward, starting at Z and working toward A. Which statement will accomplish this?

nameList.sort().reverse(); The correct statement is nameList.sort().reverse();. The nameList array needs to run the two methods sort and reverse on it. First, the sort() method orders the list into alphabetical order from A to Z. Then the reverse() method reorders the list in the reverse order, from Z to A.

Which of the following is a valid variable name in JavaScript?

number You can use number as a variable name in JavaScript, but you cannot use the others because they are all reserved words, which cannot be used as variables, functions, objects or methods. Check the course documentation for a list of reserved words.

Which event handler is commonly used when checking the choice made by the user in a select object?

onchange The onchange event handler specifies the JavaScript code to execute when the object loses focus after a user makes a selection; the event occurs only if user changes the selection from the default. Using onchange limits when the script is run to only times when a user actually changes the selection in the select list, not when the user clicks on it or tabs in simply to look at the choices.

What is the main event handler used by the JavaScript checkbox object?

onclick The checkbox object is an input object in the shape of a small square (called a check box) that the user can select, or "check," on or off by clicking it. Its main event handler is onclick and its main method is click(). The select() and onselect method and event handler are used by the select object.

Which event handler is used by the submit object?

onclick The submit object processes only the click event and thus uses only the onclick event handler.

Which of the following event handlers is used by the link object?

onmouseout The link object uses the onclick, onmouseover and onmouseout event handlers.

Which of the following is an event handler used by the form object?

onreset Event handlers used by the JavaScript form object include onreset and onsubmit. Methods used by the form object include reset() and submit().

Which of the following is an event handler processed by the form object? You answered: submit

onsubmit The onsubmit event handler is processed by the form object. Whether they are submitting forms or navigating Web pages, users generate events. JavaScript contains predetermined event handlers that deal with these events. Event handlers are designed to process events.

Which line of code demonstrates the correct JavaScript syntax to open a new window that points to www.CIWcertified.com?

open("www.ciwcertified.com","CIW",""); The correct minimum syntax for this would be open("www.ciwcertified.com","CIW","");. You open a new window by using the window object's open() method. You can launch a new window displaying an existing Web page, or you can launch an empty window and then populate it on the fly (i.e., dynamically) with content defined by your scripts. The generic syntax to open a new window using the open() method is as follows: open("URL","WindowName","Feature List") Notice that "Feature List" is one argmuent with one or multiple values.

Which X/HTML form element produces a single-line text box that displays input as mask characters such as asterisks (***) or dots to mask data entry?

password The X/HTML password element produces a single-line text box that displays input as mask characters such as asterisks or dots to mask data entry. The hidden element produces a hidden field containing a name/value pair that is submitted unseen and unchanged by the user. The text element produces a single-line text field used for data entry. The textarea element produces a scrolling text box used for data entry.

Which code correctly scripts a JavaScript prompt() method?

prompt("This text asks for user input.", "This default text appears in the text input area."); The syntax for the prompt() method is as follows: prompt("Message to user", "default response text");

Which X/HTML form element produces an option button in a set of mutually exclusive option buttons?

radio The X/HTML radio element produces an option button in a set of mutually exclusive option buttons. The checkbox element produces a check box option button used to submit a yes/no or true/false option, and allows the user to choose more than one option from a set of options. The button element produces a scriptable button other than a Submit or Reset button. The select element produces a selection list from which a single choice or multiple choices can be made.

Each form on an X/HTML page is:

represented by a separate instance of the JavaScript form object. The JavaScript form object represents an X/HTML form in JavaScript. Each form on a page is represented by a separate instance of the form object. All form objects for the page are contained within the forms array and can be accessed as forms[0], forms[1], etc.

Consider the following code (line numbers added for reference): 1 function makeBold(text) { 2 var boldText = text.bold() 3 //insert code here 4 } What must be added to Line 3 to return the text in bold to the calling statement?

return boldText; You must add the statement return boldText;. One of the most powerful features of a function is its ability to return a value to the calling statement. The return keyword is used to return values from a function.

Consider the following code: <input type="text" name="userName" onblur=" if (this.value == '') { alert('Please do not leave the Name field blank.'); this.focus(); } else { alert('Thank you, ' + this.value + '!'); } " /> In this code, the focus() method is used to:

return the user's cursor to the text box if the user left it blank. This example demonstrates three functions: (1) The use of the keyword this to refer to the current object, (2) Inline scripting that uses an if statement, and (3) The invocation of the focus() method to return the user's cursor to the text box if the user left it blank. You can use the onblur method in a similar way. With onblur, when the user moves the cursor away from an object (such as a button), a specified action will occur. This method is often used in form validation, or to remind a user to complete an action.

Consider the following JavaScript function: function myFunction(x) { //your code here } Which line should be added to the function to return to the calling statement the value of x multiplied by 2?

return x * 2 The line that should be added is return x * 2. JavaScript functions can return values to the calling statement using the return statement. The value to be returned is placed after the return keyword. The value that is returned from a function can be assigned to a variable or it can be used in an expression.

Which JavaScript event occurs when the user highlights the text in a form field?

select The JavaScript select event occurs when the user highlights text in a form field. The blur event occurs when when input focus is removed from a form element (e.g., when a user clicks the mouse button outside of a particular field). The mouseover event occurs when the user moves the mouse pointer over a link or area object. The click event occurs when the user clicks on a link or form element.

Which of the following is a valid select list declaration?

select name="mySelect"> <option> First </option> <option> Second </option> </select> The correct code is: <select name="mySelect"> <option> First </option> <option> Second </option> </select> A select list is declared with an X/HTML <select> tag. The <option> tags are used to define the items in the list, and then the list is closed with a closing </select> tag.

Most form elements use <input> tags with a specific type attribute assigned to them. Which choice lists two form elements that are created with their own X/HTML tags?

select, textarea The select and textarea elements do not use <input> tags but rather <select> and <textarea> tags. The others given here are <input> tag elements with the type attribute specifying their appearance.

ou want to call a function named ShowAd(), which will rotate an advertisement that is displayed on your Web site. You want this function to display each ad for a different amount of time, with the maximum amount of time being 4 minutes. Which statement will achieve this?

setTimeout(ShowAd, Math.random() * 240000); The correct statement is setTimeout(ShowAd, Math.random() * 240000);. The setTimeout function takes two arguments: the function or statement to execute, and the length of time until the function is triggered. In this case, a random number between 0 and 1 is generated, then multiplied by 240 (the number of seconds in 4 minutes), and the result is used for the display interval.

When you need to run a function after a certain amount of time, which method would you use?

setTimeout(function, time); The correct statement is setTimeout(function, time);. To have a method or command repeat after a set amount of time, you use the setTimeout function. It is passed the parameters for the function to run and the time to wait before running it.

comment indicators

single line comments (//) and one for multiple-line comments (/*...*/)

Which property is commonly used with the image object?

src The image object allows you to manipulate images in Internet Explorer 4.x (and later) and Firefox 1.x (and later). One of the most popular uses of the image object is to create buttons that animate whenever a mouse passes over them. This function is accomplished by dynamically changing the image object's src property.

Consider the following code: var str = "[email protected]"; Which is the best way to extract the sixth character in the string?

str.charAt(5); The best approach is str.charAt(5);. All the choices given will extract the sixth character, which is h (remember that counting begins at zero, so the sixth character is in position 5). But the charAt property is the most efficient function to accomplish this because you need only specify one character position, instead of starting and ending positions like with substring and substr. The indexOf property has an additional catch where the string may be redefined, which will likely change the fifth character.

Consider the following code: var str = "Ice Cream" Which statement will find the second occurrence of the letter e in this code?

str.indexOf("e", 3); The correct statement is str.indexOf("e", 3); because it will start to search the string at index position 3 (the space character), skipping over the first e in the string. Remember that indexes are zero-based and begin counting at zero instead of one. Remember also that JavaScript is case-sensitive.

hich of the following will determine how many characters are in the variable string str?

str.length; The statement str.length; will determine how many characters are in the variable string str. The length property does not require parentheses to be called.

You have opened a window with no address bar using JavaScript. Now you want to display the current URL in the status bar. Which line of code will achieve that result?

tatus = location.href; The code status = location.href; will achieve that result. The location object allows you to specify URLs in a script. Thus you can create buttons instead of text or graphic links to send users to different targets. You can also tie the change of location to some other portion of script. The key property of the location object you will frequently use is the href property, which specifies or returns the hypertext reference for the current or desired URL. Both the status object and the location object are subordinates to the window object. For security reasons, some browsers are beginning to disallow any change in the status bar message to ensure that you know exactly where a link is pointing before you click it. For this reason, the status property may eventually be deprecated.

String Objects

test() — Tests a string for a matching pattern; invoked by a variable representing a regular expression. split() — Splits a string and returns an array of substrings. search() — Searches a string for a string of text and returns the index position of the string, if found. match() — Similar to the search() method, except that it returns an array of matched text instead of an index position. replace() — Receives two arguments: first the string to be replaced, and then the replacement text. The replace() method is demonstrated in the following example: var myNames = "Paul, George, Ringo, John"; var myRegExp = /John/; myNames = myNames.replace(myRegExp, "Johnny"); document.write(myNames); The output from this example would be Paul, George, Ringo, Johnny. The replace() method receives two arguments. The first is the string to be replaced, and the second is the replacement text.

Which of the following JavaScript objects uses the select event?

text The JavaScript text object uses the select event. Whether they are submitting forms or navigating Web pages, users generate events. JavaScript contains predetermined event handlers that deal with these events. The select event occurs when the user selects the text in a form field.

You have created a new mobile interface for your Web application. You want to redirect users to the mobile-optimized site when they access the application from a mobile device. To do this, you can combine the appName property of the navigator object with:

the location object. You can combine the location object with the navigator object in a script to redirect to a different page depending on the type of browser used. This action is one of the most common uses for JavaScript, and it can be used to automatically direct a user to a version of the Web page that will display best in the browser used to view it. Many of the larger Web presences (such as Google, eBay, and Amazon) have several versions of the same site, and will direct each user to pages that are optimized to the specific type of browser being used.

Consider the following code: var myVar = isNaN("One"); What will be the value of myVar after execution of this code?

the value will be: true The value of myVar will be true. The isNaN() method is used to determine whether a given value is a valid number. The abbreviation isNaN stands for "is not a number." The isNaN() method takes one argument and will return true if the argument is not a number.

In JavaScript, what is the term for a built-in method that does not belong to any particular object, such as the isNaN() method?

top-level function Several built-in methods are available in JavaScript that do not belong to any particular object. These types of functions are referred to as top-level functions. They are available for use as needed throughout your scripts. Some commonly used examples are the parseInt() and parseFloat() methods. Another example is the isNaN() method, which is used to determine whether an operand is a number.

You need a three-element array containing the values Larry, Moe and Curly. Which statement will create this array?

var Stooges = ["Larry", "Moe", "Curly"]; The statement that will create this array is var Stooges = ["Larry", "Moe", "Curly"];. The variable being declared does not have brackets at the end. To properly set up the array, the elements are enclosed in brackets, not parentheses. The size of the array is dynamically adjusted to have as many elements as the highest subscript used.

Consider the following code fragment: Year: <input id="byear"/><br/> Month: <input id="bmonth"/><br/> Day: <input id="bday"/><br/> <script type="text/javascript"> var year = document.getElementById("byear").value; var month = document.getElementById("bmonth").value; var day = document.getElementById("bday").value; // Insert code here </script> Given this script, which code will record the user's birth date?

var bday = new Date(); bday.setYear(year); bday.setMonth(month - 1); bday.setDate(day); The correct code is: var bday = new Date(); bday.setYear(year); bday.setMonth(month - 1); bday.setDate(day); The bday variable is correctly defined and then assigned to using to proper methods. There is no setDay() method because the day of the week cannot be dictated by a script or developer; it is set automatically based on date information.

Which of the following demonstrates the correct way to declare a regular expression? 2

var ex = /Ringo/; Of the choices given, the correct way is var ex = /Ringo/;. One way of declaring a new regular expression is to enclose the string in forward slashes. The choice var ex = RegExp("Ringo"); is not correct because the new keyword was not used. The other choices use incorrect syntax as well.

Which of the following demonstrates the correct way to declare a regular expression?

var ex = new RegExp("Ringo"); Of the choices given, the correct way is var ex = new RegExp("Ringo");. This correct syntax includes the new keyword. The choice var ex = "/Ringo/"; will not work because the expression is contained in quotes, making it simply a string and not a regular expression. The other choices use incorrect syntax as well.

Which of the following correctly declares a variable?

var firstName; The correct variable declaration is var firstName;. When naming variables you must follow certain rules: The first character of the variable must be a letter or the underscore ( _ ) character. No other initial characters are allowed (except for $ in some versions). Subsequent characters can be letters, numbers and/or underscore characters, but symbols (other than $) are not allowed.

Consider the following text displayed on screen: Press "enter" to load file c:\test.txt Which JavaScript statement will display this? You answered: var getfile="Press \"enter\" to load file\nc:\\test.txt"; alert(getfile);

var getfile="Press \"enter\" to load file\nc:\\test.txt"; alert(getfile); One answer does not have the second backslash after c:. Another answer uses\l, but is supposed to use \n. Another answer does not escape the quotation marks and uses \l instead of \n.

Which JavaScript code segment correctly determines which radio button has been selected from a radio button group named myRadio in a form named myForm?

var len = myRadio.length; var myVar = ""; for(var idx = 0; idx < len; idx++) { if(document.myForm.myRadio[idx].checked) { myVar = document.myForm.myRadio[idx].value; } } The correct code is: var len = myRadio.length; var myVar = ""; for(var idx = 0; idx < len; idx++) { if(document.myForm.myRadio[idx].checked) { myVar = document.myForm.myRadio[idx].value; } } The checked property rather than the selected property is used for radio buttons. In this example, the if statement must include the idx variable with the checked property.

Which code fragment will create an unordered list using the contents of myArray and display it on the Web page?

var list = "<ul>"; for (i = 0; i < myArray.length; i++) { list = list + "<li>" + myArray[i] + "</li>"; } list = list + "</ul>"; document.write(list); The best answer is: var list = "<ul>"; for (i = 0; i < myArray.length; i++) { list = list + "<li>" + myArray[i] + "</li>"; } list = list + "</ul>"; document.write(list); This code will properly iterate through all the elements in myArray, from 0 to length - 1, and create the markup for an unordered list which is appended to the list variable.

Which of the following JavaScript code segments properly accesses the numeric value of the array number returned when a user selects an option from a select object named mySelect in a form named myForm?

var myVar; myVar = document.myForm.mySelect.selectedIndex; The correct code is: var myVar; myVar = document.myForm.mySelect.selectedIndex; The selectedIndex property specifies or returns an integer value of the array number of the selected option.

Which of the following demonstrates the proper way to format a string to appear on two lines?

var rhyme = "Hey diddle diddle\nThe cat and the fiddle"; The correct syntax is var rhyme = "Hey diddle diddle\nThe cat and the fiddle";. This statement correctly uses the escape character syntax \n . Using the <br/> tag is another approach that would work to insert a line break, but only if the <br/> tag were enclosed in quotes. Without the quotes, the interpreter will think it is a variable or code and return a syntax error.

Which of the following JavaScript objects uses the onerror event handler?

window The JavaScript window object uses the onload, onunload and onerror event handlers.

The continue statement can be used only:

within a for loop or a while loop. The continue statement can be used only within a for loop or a while loop. The continue statement is used to force the flow of control back to the top of a loop. You can think of continue as a "skip" or bypass command. When execution hits a continue statement, all statements between it and the end of the loop block are skipped, and execution returns to the top of the loop. The test condition for the loop is then evaluated to determine whether the loop should execute again. The switch statement is used in place of multiple else...if statements. The break statement provides a way to exit a loop that would otherwise continue to execute, and is usually found inside an if clause.

toUpperCase() method

works as a function because it returns the answer variable after converting it to uppercase letters:

The main advantage of validating data on the client side using JavaScript is that:

you can prevent information from passing to the server until it is correct. Perhaps the most common need from a Web developer's perspective is the ability to retrieve and verify data from the user through an X/HTML form. The main advantage of validating data on the client side using JavaScript is that you can prevent information from passing to the server until it is correct. This saves bandwidth, and it is faster than sending the information, then validating it, finding an error and sending it back for correction.

When are semicolons generally used in JavaScript?

To separate statements when there is more than one statement present

What is the purpose of the document.write() method?

To write text into the document dynamically as the page loads in the browser.

The = and == operators

Used in a script, this statement would assign the value of "Nancy" to the variable userName. userName = "Nancy"; If you wanted to compare userName to "Nancy", you would use the following code: userName == "Nancy";

similar to JavaScript in purpose and implementation?

VBScript

fundamental concepts

Variables, data types, expressions and operators

The + operator

+ is the operator for arithmetic addition or for string concatenation. The += operator appends the value of one string to another, instead of combining the operands into a single string. For example, "Mad" + " " + "Hatter" will result in "Mad Hatter". You can do the same thing with the += operator and get the same output, like so: var Name = "Mad" Name+= " " Name+= "Hatter"

variable

- A named space of memory that holds a value. The value can change depending on a condition or information passed to the program, or by reassignment of a new value. Data Types: - number - Any numeric value (e.g., 3, 5.3, or 45e8) - string - Any string of alphanumeric characters (e.g., "Hello, World!", "555-1212" or "KA12V2B334") - Boolean - True or false values only - Object - A reference to a JavaScript object - null - null value (e.g., if a user enters nothing in a text box then submits the form, the text box has null value) Note: Compare null value to empty value, in which a user types and enters only a space in the text box; the value of the text box is empty, but can be counted as a character. - undefined - Occurs when a variable has no value assigned yet. Note: The undefined value is different from null, which is actually a value. Naming variables: - The first character of the variable must be a letter or the underscore ( _ ) character. No other initial characters are allowed. - Subsequent characters can be letters, numbers and/or underscore characters. Common naming convention: - use two words with no space between them, and capitalize the second word but not the first. e.g camelCase

JavaScript

- A scripting language for adding dynamic interactivity to Web pages. Generally used on the client side but can also be used on the server side. - Checks object references at run time ("dynamic binding") - an object-based scripting language. - can make a Web page rich and dynamic. - functionality is performed on the client side, which reduces processing time dramatically. - JavaScript was first supported in Navigator version 2.0 - key uses for scripting languages such as JavaScript is to allow more complex programs, created by programming languages such as C++ and Java, to work together. -an interpreted language (as opposed to a compiled language) and does not support the more complex features of a full programming language. - JavaScript is eventdriven - JavaScript is platform-independent - JavaScript enables quick development - JavaScript is easy to learn.

Code will not be displayed in the browser

<script language="JavaScript"> <!-- // JavaScript code var x = 10; //--> </script>

characteristic of event-driven programming

Events can trigger functions.

Consider the following code: var myVar; myVar = confirm("continue?"); What is the data type of the value of myVar after execution?

Boolean The confirm() method returns a value of type Boolean. Boolean values are true and false, and the confirm() method results in only these two values.

scripting language

- A scripting language is a simple programming language designed to enable computer users to write useful programs easily. - Scripting languages are subsets of larger, more complicated programming languages. - Programming languages are compiled, whereas scripting languages are interpreted at runtime, meaning that they are not compiled to any particular machine or operating system. - platform independent.

Hypertext Markup Language (HTML)

- X/HTML is not a programming language but a markup language used to format Web pages, and it has many limitations. - X/HTML positions text and graphics on a Web page, but offers limited interactivity within the Web page.

alert() method

- allows you to communicate with the user <script type="text/javascript"> <!-- // Create an alert() method alert("good morning"); //--> </script

Using JavaScript best practices, which X/HTML tag correctly targets a block of JavaScript code for browsers that support JavaScript version 1.5?

<script language ="JavaScript 1.5">

document.write() method

- allows you to create text that is dynamically written to the window as the script is executed(used to output data to the X/HTML stream). <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Example: document.write</title> </head> <body> <script type="text/javascript"> <!-- document.write("How wonderful to meet you, " + prompt("Hello, my name is James. What's yours?", "") + "."); //--> </script> </body> </html> - -----customize a page for the user--------------- <script type="text/javascript"> <!-- /************************************************ The return value of a prompt() method concatenated into a document.write() statement ***********************************************/ document.write("<h4>Welcome, " + prompt("What is your name?", "Thank you for entering your name here") + "</h4>"); //--> </script>

Object-oriented language

- is a collection of individual objects that perform different functions, rather than a sequence of statements that collectively perform a specific task. - JavaScript is not object-oriented because it does not allow for object inheritance and subclassing in the traditional sense.

prompt() method

- requests user input through a text field within a dialog box. - -prompt("Message to user", "default response text"); <script type="text/javascript"> <!-- // Concatenate a prompt() into an alert() statement alert("Good morning, " + prompt("What is your name?", "") + "."); //--> </script>

The confirm() method

- returns a value of either true or false - -confirm("Question to the user?"); <script type="text/JavaScript"> <!-- /****************************************** The return value of a confirm() method concatenated into an alert() statement ******************************************/ alert("The confirm returned " + confirm("Do you want to proceed?") + "."); //--> </script>

event-driven model

- whenever you click an item on a Web page, an event occurs. - Event triggers can be as simple as the user clicking a button, clicking or moving the mouse over a hyperlink, or entering text into a text field.

JavaScript Expressions

1. Assignment (=) (Assignment) Assigns a value to a variable myNumber = 25; The value 25 has been assigned to the variable myNumber 2. Arithmetic (+) (Addition) Evaluates to a number 25 + 75; This expression evaluates to the sum of 25 and 75 3. String (+) concatenation Evaluates to a string "Hello, " + "Sandy"; This evaluates to a new string that says "Hello, Sandy". 4. Logical < (less than comparison) or >= (greater than or equal comparison). Evaluates to true or false 25 < 75; Because 25 is less than 75, this expression evaluates to the Boolean value of true. 25 >= 75; Because 25 is not greater than or equal to 75, this expression evaluates to the Boolean value of false. 5. Comparison (==) (equal operator) Compares two values and returns a true or false value z == 10 Returns true if z is 10 == 6. Conditional (?) (ternary operator) Makes decisions in a script; the expression (condition) will return either true or false, then evaluate the corresponding expression (a > b) ? a++ : a--; If a is greater than b, then the value of a will be increased by 1; if a is less than b, then the value of a will be decreased by 1

object-oriented program

A collection of individual objects that perform different functions

In JavaScript, what is a data type?

A definition of the type of information a variable holds In JavaScript, a data type is a definition of the type of information a variable holds. A variable is a named space of memory. It is a container that holds a value, which you can then access repeatedly in your script. Variables can store five data types in JavaScript: number, string, Boolean, Object and null. An additional data type -- undefined -- occurs when a variable has no value assigned.

alert(confirm("Continue?"));

A dialog box displaying Continue? with two buttons labeled Yes and No, followed by a dialog box displaying True or False depending on user input Often in programming, you will want to ask the user a simple yes-or-no (true-or-false) type of question. You can do this with a message box that provides both OK and Cancel buttons, using the confirm() method. It is similar to the alert() method with one significant exception: The confirm() method returns a value of either true or false, whereas the alert() method has no return value. This return value can be captured and used in your scripts. In this example, the confirm() method will return true or false based on what button the user chooses. The alert() method will then display the return value of the user's choice in a separate di

When more than one method is defined in a single line of JavaScript code, which method will execute first?

A method defined inside another method will always be executed before the outer method.

object

A programming function that models the characteristics of abstract or real "objects" using classes.

dot notation

A reference used to access a property or method of an object. objectName.methodName(); objectName.propertyName;

PHP (PHP Hypertext Preprocessor)

A server-side X/HTML-embedded scripting language for developing dynamic Web sites.

In programming, what is an object?

An object is a programming function that models the characteristics of abstract or real "objects." An object encapsulates predesignated attributes and behaviors, and is often grouped with similar objects into classes.

Why does the alert() method interrupt the workflow of an application?

Because the alert() method results in a modal dialog The alert dialog box is modal in nature. This means that the user must acknowledge the dialog box by clicking the OK button in the dialog (or pressing ENTER on the keyboard) before being allowed to navigate further with the present browser window.

Where does client-side JavaScript code reside, and how is it activated?

Client-side JavaScript code resides within an X/HTML document, and in some cases is embedded directly within certain X/HTML tags (which is called inline scripting). JavaScript is activated by an event, to which the script is instructed to respond with a designated action.

In programming, which term refers to the syntax used to associate an object's name with its properties or methods?

Dot notation.

event handler

In JavaScript, a piece of code that processes and responds to an event by intercepting the event and associating executable code with it.

How do JavaScript, JScript, VBScript and the ECMA scripting standard differ?

JScript, ECMAScript and VBScript are similar but different implementations, or "flavors," of JavaScript. JScript is the Microsoft version of Netscape's JavaScript. Minor differences exist in the implementations of JavaScript and JScript, with some differences causing compatibility problems. The ECMA flavor intends to diminish the differences between the JavaScript and JScript flavors. ECMA attempted to promote this standard as "ECMAScript," but the name did not gain widespread popularity. VBScript is similar in purpose to JavaScript, but is rarely used anymore in Web pages. It was created by Microsoft as a subset of the Visual Basic programming language.

How does JavaScript allow you to communicate with Web users?

JavaScript allows you to script actions that occur in response to user events. You can display messages to users, request input from users, and incorporate user input in response messages. JavaScript enables you to communicate in these ways by manipulating objects, and by naming and using variables.

What advantage do scripting languages such as JavaScript offer over X/HTML?

Scripting languages offer increased user interaction

What is the term for JavaScript's server-side technology?

Server-Side JavaScript (SSJS) is JavaScript's server-side scripting environment. - mplementations of server-side JavaScript include LiveWire and work with back-end server processes. - Originally created for Netscape Enterprise Server (and called LiveWire), SSJS is the next generation of the server-side JavaScript language

Which method displays a simple message to the user but does not take any response?

The alert() method is simple JavaScript that allows you to communicate with the user by displaying a message. The open() method opens a new browser window but does not necessarily include a communication. The prompt() method allows you to ask the user a question and receive his input. The confirm() method allows you to ask the user a yes-or-no type question, to which the user responds by clicking one button or the other.

document.write(navigator.appVersion)

The appName property returns a string value indicating the name of the client browser. The appVersion property returns a string value indicating the version number of the client browser, as well as the client's platform.

Consider the following code: var myVar1 = "25"; var myVar2 = 25; What is the difference between myVar1 and myVar2?

The data type The data type is different: myVar1 is a string type and myVar2 is a number type. When assigning literal values to variable names, you place string values inside quotation marks. Numeric values are not placed inside quotation marks.

alert("Hello " + prompt("what is your name?", "");

The dialog will display: Hello Jon

Consider the following code: var yearOfBirth = 1978; alert("YearOfBirth"); What would the resulting dialog box display?

The dialog will display: YearOfBirth The resulting dialog box would display YearOfBirth because that is the text placed within the quotation marks in the alert("") statement. JavaScript is case-sensitive, so when you declare a variable, use the name consistently or your script will not work properly. When assigning literal values to variable names, you place string values inside quotation marks. Numeric values are not placed inside quotation marks.

Which of the following statements uses correct syntax for the alert() method?

alert("This is a message for the user"); The syntax for using the alert() method is as follows: alert("message"); The message must be within quotes. The alert() method is a method of the window object, not the document object. In this example, the text "This is a message for the user" is given as the argument to the alert() method. If the code in this example were executed, a dialog box with the text "This is a message for the user" would appear on the user's screen.

Concatenation

combine text strings, especially in conjunction with the prompt() and alert() methods.

Declaring variables

declare a variable using the var keyword: - var correctAnswer; (does not hold any value) - var correctAnswer1 = 20; (an initial value to the variable) - var correctAnswer2 = "Yes"; (an initial value to the variable)

Mathematical precedence

dictates the order in which operations will be worked: First, the script will work within the parentheses, doing multiplication and division first, then addition and subtraction next. Then the script will go outside the parentheses and work multiplication/division first, then work left to right doing addition and subtraction. This fact is important to know when you are creating complex formulas using JavaScript.

Which of the following uses correct syntax to display text as part of a Web page?

document.write("Text to display"); The document.write() method allows you to create text that is dynamically written to the Web page in the browser window as the script is executed. You can write out plain text or you can add X/HTML tags to the text being written.

Which of the following is a variable data type supported by JavaScript?

in JavaScript, variables can store any of five data types: string, number, Boolean, Object and null. An additional data type -- undefined -- occurs when a variable has no value assigned. The string data type can be used for any alphanumeric characters, including text and numbers not used for math. The number data type is used exclusively for numeric values, to enable mathematical operations.

The ++ and -- operators

increment (++) and decrement (--) operators can be placed either before or after an operand. If the increment or decrement operator is placed before the operand, the operation occurs immediately. If the increment or decrement operator is placed after the operand, the change in the operand's value is not apparent until the next time the operand is accessed in the program. var i = 1; document.write("First access: " + i++); document.write("<br />Second access: " + i); The output of the preceding piece of code would be as follows: First access: 1 Second access: 2 As the preceding output demonstrates, the next time the variable i is accessed in the program, it contains the incremented value. Consider the following example: var i = 1; document.write(++i); The output of this piece of code would be 2 because the increment operator is placed before the operand, causing the operation to occur immediately.

Which code correctly scripts a JavaScript prompt() method without displaying a default response to the user?

prompt ("This text asks for user input.", ""); The syntax for the prompt() method is as follows: prompt("Message to user", "default response text"); If you do not want default text in the text-entry area, you must follow the initial message with a comma and an empty set of quotation marks. This syntax is required for the prompt() method.

Methods

the actions that an object can be made to perform. - Methods often describe the actions that an object performs with its properties.

Literals

the actual data values you provide in JavaScript Literal Type Example: - Integer literal - 56 - Floating-point literal - 23.45 - String literal - "Howdy!" - place string values inside quotation marks. - Numeric values are not placed inside quotation marks.

Values

the specific qualities of properties. For instance, the statement color="red" assigns a value to a property.

Which statement uses proper JavaScript syntax for declaring variables?

var firstName = "Sal", lastName = "Fiore"; The example that uses the correct syntax is var firstName = "Sal", lastName = "Fiore";. Declaring a variable means telling JavaScript that a specific named variable exists. In JavaScript, you can declare a variable using the var keyword: var correctAnswer; You can also assign an initial value to the variable when you declare it. For example: var correctAnswer1 = 20; var correctAnswer2 = "Yes"; You use the equal sign (=) to assign the value to the variable. You can create and assign values to multiple variables with a single var keyword, as shown in the following example: var correctAnswer1 = 20, correctAnswer2 = "Yes"; Note the use of a comma to separate the variable names in this example.

Which of the following variable declarations would result in an error?

var myVariable; myVariable2; There are many valid ways to declare variables. A variable can have a value assigned at declaration, but this is not a requirement. Of these choices, the variable declaration that would result in an error is var myVariable; myVariable2; because a semicolon ended the first declaration and the second declaration did not use the var keyword.

Concatenating variables

var userName = "Julio"; document.write("We thank " + userName + " for visiting our site.");

Which of the following JavaScript code segments correctly concatenates the variables x and y into a document.write() statement?

var x = 10, y = 20; document.write("x is " + x + " and y is " + y + "."); because (+) successfully concatenates, and the quotes must surround the text you want to display rather than the variables.

camelCase style

variants: - Lower camelCase (the first letter is lowercase) —Variable names, function names and object names use lower camelCase - Upper CamelCase (the first letter is capitalized) — Classes (e.g. anything instantiated with the new keyword) normally use upper CamelCase. Do not use for: - event handlers (e.g., onClick, onLoad) Use for: - call functions [e.g., onClick()]

Properties

various attributes of an object, such as height, color, font size, sentence length and so forth.


Conjuntos de estudio relacionados

California Adjuster PSI Flash Cards 3

View Set

Ch. 21, 22 + 23 Ethics/Legal/Managing Pt. Care Practice Questions

View Set

Economics chapter 23-25 multiple choice

View Set

Comprehensive Medical Coding Exam 1 Review

View Set

Sports Civ Midterm Quiz Questions

View Set

Geology 1403 Lab Practical Final

View Set

Chapter 9 Practice Quiz Communication in the Digital Age

View Set

PHIL: Ethics Fall 2017 - Unit Two

View Set

Biology Exam 3 - (Chapters 14, 15, 16 & 18)

View Set