Web Programming C298 (JavaScript)

Pataasin ang iyong marka sa homework at exams ngayon gamit ang 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.

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. - 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. - Scripting languages offer increased user interaction over X/HTML - 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.

Programmers refer to attributes and values as

" properties ."

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.

casting

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

user agent

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

Which of the following statements is true?

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

Modulus operator (%)

is an arithmetic operator that performs division and calculates the remainder. All arithmetic operators become assignment operators when placed in front of the = character.

Variable data type supported by JavaScript

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. - Boolean values are true and false, and the confirm() method results in only these two values.

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.

Properties

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

scripting language

- 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. - Scripting languages offer extended functionality, but are easier and quicker to learn than full programming languages.

operators

- The initial ! operator means NOT but it applies only to the first statement in parentheses, not both statements !(myVar == 0) || myVar2 <= 20; - 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. - equal (===) - not equal (!==) - 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. - The increment operator (++) increases the value of the supplied operand by one. If the increment operator is placed before the operand ((document.write(++counter)), 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.

alert() method

- allows you to communicate with the user <script type="text/javascript"> <!-- // Create an alert() method alert("good morning"); //--> </script - alert() method interrupts the workflow of an application because the alert() method results in a modal dialog. - The alert() method allows you to communicate with the user by displaying a message but does not take any response. It dies require clicking OK or pressing enter.

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>

onload event handler

- execute JavaScript code when a page is loaded - uses <body> tag Message when you hit home or back - The onload event is "implied" - any code that is not included in a function will execute when the page is loaded

onunload event handler

- execute script immediately when an XHTML page is closed -Uses <body> tag ex: <!-- onunload event handler calls alert() method --> <body onunload = "alert('Goodbye, ' + userName + '. Hurry back!');">

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.

var myVar1 = "25"; var myVar2 = 25; What is the difference between myVar1 and myVar2?

- myVar1 is a string type, inside quotation marks. - myVar2 is a number type not placed inside quotation marks.

prompt() method

- requests user input through a text field within a dialog box. 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. <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

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

floating-point calculation

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

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

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;

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.

PHP (PHP Hypertext Preprocessor)

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

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

What is an event handler?

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

event-driven programming

Events can trigger functions.

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.

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.

What is concatenation?

In JavaScript, concatenation is often used to combine text strings for further manipulation(reduce duplication).

Dot notation

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

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. JavaScript methods to communicate with users: The alert(), prompt(), confirm() and document.write() methods.

Relationship between JavaScript and Java

JavaScript and Java are different languages and have no relationship.

object-based language

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

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.

JavaScript - server-side technology

Server-Side JavaScript (SSJS) is JavaScript's server-side scripting environment. - implementations 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

Assignment operator

The += operator is an assignment operator. All arithmetic operators become assignment operators when placed in front of the = character.

Comparison operator

The == and === operators are a comparison operator. All arithmetic operators become assignment operators when placed in front of the = character. The modulus operator (%) is an arithmetic operator that performs division and calculates the remainder. can be an arithmetic operator to perform addition or a string operator to perform concatenation.

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

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.

The window object.

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

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.

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.

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.

Order of operations

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. EX: The statement is evaluated as (8 / 4) = 2 * 2 =4 + 1 (result of 2 / 2), which equals 5

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

The onload event

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

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.

<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

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

fundamental concepts

Variables, data types, expressions and operators

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.

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.

confirm() method -

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

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.

Concatenation

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

parseFloat()

converts a string to its floating-point decimal equivalent

parseInt()

converts a string to its integer equivalent

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.

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.

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

link an external JavaScript file to an X/HTML doc

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.

VBScript

similar to JavaScript in purpose and implementation?

comment indicators

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

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 correctly declares a variable?

var firstName; or _lastName 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.

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()]

toUpperCase() method

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


Kaugnay na mga set ng pag-aaral

Biology- Sustainability & Interdependence

View Set

What Was Ancient Civilization in Greece Like?

View Set

Educational Technology Terminology

View Set

Chapter 7 Membrane Structure and Function

View Set

Anatomy and Physiology 1 Chapter 6 Bone Tissue

View Set