UCCD2323 JS Notes.pdf
Document Details
Uploaded by Deleted User
Tags
Full Transcript
UCCD 2323: Front-End Web Development Chapter 6 – JavaScript: Introduction to Scripting COPYRIGHT © 2016 PEARSON EDUCATION, INC., HOBOKEN NJ ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All...
UCCD 2323: Front-End Web Development Chapter 6 – JavaScript: Introduction to Scripting COPYRIGHT © 2016 PEARSON EDUCATION, INC., HOBOKEN NJ ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. -Applications based on the ideas originating from the web are becoming ubiquitous; the technologies we once exclusively used to develop client-side web applications, executed in the browser, have spread to other domains. Now, we can use similar or even the same ideas and techniques to develop standard desktop applications (for example, code editors like Atom.io), hybrid mobile applications (for example Netflix), server-side applications (by using Node.js), and even applications for embedded devices (with Espruino or Tessel). In the history of computing, it has been very rare that a particular skill set is so easily transferable and useful across so many different domains. - JavaScript development for the browser- can easily be transferred to other application domains. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. The JavaScript eco-system: JavaScript applications can nowadays be executed on different devices (desktop computers, mobile devices, servers, and even on embedded devices). ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. JavaScript consists of a close relationship between objects and prototypes, and functions and closures; concepts applicable across multiple domains. JavaScript is much more functionally oriented, which means there are some fundamentally different concepts with respects to most other languages, such as: Functions as first-class objects and Function closures Function closures are a concept that is generally poorly understood, but at the same time it fundamentally and irrevocably exemplifies the importance of functions to JavaScript. For now, it’s enough to know that a function is a closure when it keeps alive (“closes over”) the external variables used in its body. In addition to closures, we’ll thoroughly explore the many different aspects of functions themselves in chapters 4 and 6, as well as identifier scopes in chapter 5. Scopes are particularly interesting because, up to recently, the scoping rules in JavaScript were more limited than the scoping rules in other C-like languages – up to the latest version of JavaScript there were no block level variables (as in other C-like languages), instead we had to rely only on global variables and function-level variables. - Prototype-based object orientation Unlike other main-stream languages (such as C#, Java, or Ruby) which use class-based object orientation, JavaScript is the only widely-used language that uses prototypes. In prototype-based object orientation, an object is merely a collection of properties with some values, and every object can have a prototype to which a search for a particular property can be delegated to, when the object itself does not have that property. Prototype-based object orientation in particular is the source of woes for many developers. Often, when developers come to JavaScript from class-based languages, for example Java, they try to use JavaScript as it were Java, essentially writing Java’s class-based code using the syntax of JavaScript. Then, for some reason, developers often get surprised when the results differ from what they expect. This is why we’ll go deep into prototypes, how prototype-based object-orientation works, and how it is implemented in JavaScript. Understanding the strong relationship between these concepts can vastly improve our JavaScript programming ability, giving us a strong foundation for any type of application development, regardless of whether our JavaScript code will be executed within a web page, a desktop app, a mobile app, or on the server. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. JavaScript ▪ Scripting language which is used to enhance the functionality and appearance of web pages. Before you can run code examples with JavaScript on your computer, you may need to change your browser’s security settings. ▪ IE9 prevents scripts on the local computer from running by default ▪ Firefox, Chrome, Opera, Safari (including on the iPhone) and the Android browser have JavaScript enabled by default. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Debugging JavaScript used to mean using alert to verify the value of variables. Fortunately, the ability to debug JavaScript code has dramatically improved, in no small part due to the popularity of the Firebug developer extension for Firefox. Similar tools have been developed for all major browsers: ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Firebug – The popular developer extension for Firefox that got the ball rolling (http://getfirebug.com/). Chrome Dev Tools – developed by the Chrome team, used in Chrome and Opera Firefox DevTools – a tool included into Firefox, built by the Firefox team. F12 developer tools – Included in Internet Explorer and Microsoft Edge. WebKit Inspector – used by Safari. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. We focus on Open Chrome DevTools Select More Tools > Developer Tools from Chrome's Main Menu or Right-click a page element and select Inspect. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Using ‘var’ keyword ▪ Variables declared with var are function-scoped, meaning they are only visible within the function where they are declared. ▪ They can also be globally scoped if declared outside of any function. ▪ Example, var x = 10; ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Using ‘let’ keyword ▪ Variables declared with let are block-scoped, meaning they are only visible within the block (statement or compound statement) where they are declared. ▪ let allows you to reassign values. ▪ Example, let y = 20; ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Using ‘const’ keyword ▪ Variables declared with const are also block- scoped. ▪ The value assigned to a const variable cannot be reassigned after declaration. ▪ It is commonly used for values that should not be changed. ▪ Example, const z = 30; ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Variables can also be declared without an initial value, and you can assign a value to them later: Example, ▪ let name; // Variable declaration without initialization ▪ name = "John"; // Variable assignment Use const by default and only use let when you know the variable's value will change. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Valid variable names must adhere to certain rules and conventions. Identifier Rules ▪ Variable names in JavaScript are called "identifiers." ▪ Identifiers must begin with a letter (a-z, A-Z), underscore (_), or dollar sign ($). ▪ After the first character, identifiers can also contain digits (0-9). Reserved Words ▪ You cannot use JavaScript reserved words as variable names. These include keywords like if, else, while, function, etc. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Case Sensitivity ▪ JavaScript is case-sensitive, so myVariable and MyVariable are considered different variables. Camel Case Convention ▪ It's a common convention in JavaScript to use camel case for variable names (e.g., myVariable, totalAmount, calculateSum), especially for variables and functions. Avoid Single Letter Names ▪ While technically valid, it's good practice to use meaningful names that convey the purpose of the variable. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Examples of invalid variable names // Invalid: Starts with a number let 1stPlace = "First"; // Invalid: Contains a special character other than underscore or dollar sign let my-variable = "Invalid"; // Invalid: Reserved word let if = "Condition"; // Invalid: Space in the variable name let my variable = "Invalid"; ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Array Literal ▪ You can create an array using square brackets and separating elements with commas. ▪ Example, let fruits = ['apple', 'orange', 'banana’]; Array Constructor ▪ You can use the Array constructor to create an array. ▪ Example, let numbers = new Array(1, 2, 3, 4, 5); ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Empty Array ▪ You can create an empty array and later add elements to it. ▪ Example, let emptyArray = []; emptyArray.push('first', 'second'); Array.from() ▪ You can use Array.from() to create an array from an iterable or array-like object. ▪ Example, let newArray = Array.from('hello’); // Result: ['h', 'e', 'l', 'l', 'o'] ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Array of a Specific Length ▪ You can create an array of a specific length and fill it with default values. ▪ Example, let newArray = new Array(3); // Creates an array with length 3 // Result: [undefined, undefined, undefined] let filledArray = new Array(3).fill(0); // Creates an array with length 3, filled with 0 // Result: [0, 0, 0] ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Spread Operator ▪ You can use the spread operator (...) to create a new array by spreading elements from an existing array or iterable. ▪ Example, let originalArray = [1, 2, 3]; let newArray = [...originalArray]; ©1992-2012 by Pearson Education, Inc. All Rights Reserved. We begin with a simple script that displays the text "Welcome to JavaScript Programming!" in the HTML5 document. All major web browsers contain JavaScript interpreters, which process the commands written in JavaScript. The JavaScript code and its result are shown in Fig. 6.1. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Spacing displayed by a browser in a web page is determined by the HTML5 elements used to format the page Often, JavaScripts appear in the section of the HTML5 document The browser interprets the contents of the section first The tag indicates to the browser that the text that follows is part of a script. Attribute type specifies the scripting language used in the script—such as text/javascript ©1992-2012 by Pearson Education, Inc. All Rights Reserved. The script Element and Commenting Your Scripts The tag indicates to the browser that the text which follows is part of a script. The type attribute specifies the MIME type of the script as well as the scripting language used in the script—in this case, a text file written in javascript. In HTML5, the default MIME type for a is "text/html", so you can omit the type attribute from your tags. You’ll see it in legacy HTML documents with embedded JavaScripts. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. A string of characters can be contained between double quotation (") marks (also called a string literal) ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Browser’s document object represents the HTML5 document currently being displayed in the browser ▪ Allows a you to specify HTML5 text to be displayed in the HTML5 document Browser contains a complete set of objects that allow script programmers to access and manipulate every element of an HTML5 document Object ▪ Resides in the computer’s memory and contains information used by the script ▪ The term object normally implies that attributes (data) and behaviors (methods) are associated with the object ▪ An object’s methods use the attributes’ data to perform useful actions for the client of the object—the script that calls the methods ©1992-2012 by Pearson Education, Inc. All Rights Reserved. The parentheses following the name of a method contain the arguments that the method requires to perform its task (or its action) Every statement should end with a semicolon (also known as the statement terminator), although none is required by JavaScript JavaScript is case sensitive ▪ Not using the proper uppercase and lowercase letters is a syntax error ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. The document object’s writeln method ▪ Writes a line of HTML5 text in the HTML5 document ▪ Does not guarantee that a corresponding line of text will appear in the HTML5 document. ▪ Text displayed is dependent on the contents of the string written, which is subsequently rendered by the browser. ▪ Browser will interpret the HTML5 elements as it normally does to render the final text in the document ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. A Note About Embedding JavaScript Code into HTML5 Documents JavaScript code is typically placed in a separate file, then included in the HTML5 document that uses the script. This makes the code more reusable, because it can be included into any HTML5 document—as is the case with the many JavaScript libraries used in professional web development today. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. A script can display Welcome to JavaScript Programming! in many ways. Figure 6.2 displays the text in magenta, using the CSS color property. Method write displays a string like writeln, but does not position the output cursor in the HTML5 document at the beginning of the next line after writing its argument ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. The + operator (called the “concatenation operator” when used in this manner) joins two strings together ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Displaying Text in an Alert Dialog Dialogs ▪ Useful to display information in windows that “pop up” on the screen to grab the user’s attention ▪ Typically used to display important messages to the user browsing the web page ▪ Browser’s window object uses method alert to display an alert dialog ▪ Method alert requires as its argument the string to be displayed window.alert() ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Escape Sequences When a backslash is encountered in a string of characters, the next character is combined with the backslash to form an escape sequence. The escape sequence \n is the newline character. It causes the cursor in the HTML5 document to move to the beginning of the next line. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Scripting ▪ Gives you the ability to generate part or all of a web page’s content at the time it is shown to the user ▪ Such web pages are said to be dynamic, as opposed to static, since their content has the ability to change ©1992-2012 by Pearson Education, Inc. All Rights Reserved. The next script creates a dynamic welcome page that obtains the user’s name, then displays it on the page. The script uses another predefined dialog box from the window object—a prompt dialog—which allows the user to enter a value that the script can use. Figure 6.5 presents the script and sample output. window.prompt() ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Keywords are words with special meaning in JavaScript Keyword var ▪ Used to declare the names of variables ▪ A variable is a location in the computer’s memory where a value can be stored for use by a script ▪ All variables have a name, type and value, and should be declared with a var statement before they are used in a script A variable name can be any valid identifier consisting of letters, digits, underscores ( _ ) and dollar signs ($) that does not begin with a digit and is not a reserved JavaScript keyword. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Declarations end with a semicolon (;) and can be split over several lines, with each variable in the declaration separated by a comma (forming a comma-separated list of variable names) ▪ Several variables may be declared in one declaration or in multiple declarations. Comments ▪ A single-line comment begins with the characters // and terminates at the end of the line ▪ Comments do not cause the browser to perform any action when the script is interpreted; rather, comments are ignored by the JavaScript interpreter ▪ Multiline comments begin with delimiter All text between the delimiters of the comment is ignored by the interpreter. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. The window object’s prompt method displays a dialog into which the user can type a value. ▪ The first argument is a message (called a prompt) that directs the user to take a specific action. ▪ The optional second argument is the default string to display in the text field. Script can then use the value that the user inputs. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. A variable is assigned a value with an assignment statement, using the assignment operator, =. The = operator is called a binary operator, because it has two operands. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. null keyword ▪ Signifies that a variable has no value ▪ null is not a string literal, but rather a predefined term indicating the absence of value ▪ Writing a null value to the document, however, displays the word “null” Function parseInt ▪ converts its string argument to an integer JavaScript has a version of the + operator for string concatenation that enables a string and a value of another data type (including another string) to be concatenated ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Our next script illustrates another use of prompt dialogs to obtain input from the user. Figure 6.7 inputs two integers (whole numbers, such as 7, –11, 0 and 31914) typed by a user at the keyboard, computes the sum of the values and displays the result. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Variable names correspond to locations in the computer’s memory. Every variable has a name, a type and a value. When a value is placed in a memory location, the value replaces the previous value in that location. When a value is read out of a memory location, the process is nondestructive. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. JavaScript does not require variables to have a type before they can be used in a script A variable in JavaScript can contain a value of any data type, and in many situations, JavaScript automatically converts between values of different types for you JavaScript is referred to as a loosely typed language When a variable is declared in JavaScript, but is not given a value, it has an undefined value. ▪ Attempting to use the value of such a variable is normally a logic error. When variables are declared, they are not assigned default values, unless specified otherwise by the programmer. ▪ To indicate that a variable does not contain a value, you can assign the value null to it. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. The basic arithmetic operators (+, -, *, /, and %) are binary operators, because they each operate on two operands JavaScript provides the remainder operator, %, which yields the remainder after division Arithmetic expressions in JavaScript must be written in straight-line form to facilitate entering programs into the computer ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Parentheses can be used to group expressions as in algebra. Operators in arithmetic expressions are applied in a precise sequence determined by the rules of operator precedence: ▪ Multiplication, division and remainder operations are applied first. ▪ If an expression contains several of these operations, operators are applied from left to right. ▪ Multiplication, division and remainder operations are said to have the same level of precedence. ▪ Addition and subtraction operations are applied next. ▪ If an expression contains several of these operations, operators are applied from left to right. ▪ Addition and subtraction operations have the same level of precedence. When we say that operators are applied from left to right, we are referring to the associativity of the operators. Some operators associate from right to left. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. if statement allows a script to make a decision based on the truth or falsity of a condition ▪ If the condition is met (i.e., the condition is true), the statement in the body of the if statement is executed ▪ If the condition is not met (i.e., the condition is false), the statement in the body of the if statement is not executed Conditions in if statements can be formed by using the equality operators and relational operators ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Equality operators both have the same level of precedence, which is lower than the precedence of the relational operators. The equality operators associate from left to right. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. The script in Fig. 6.14 uses four if statements to display a time-sensitive greeting on a welcome page. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Date object ▪ Used acquire the current local time ▪ Create a new instance of an object by using the new operator followed by the type of the object, Date, and a pair of parentheses ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 1. String 2. Number 3. Bigint Note: JavaScript BigInt is a new datatype (ES2020) that can be used to store integer values that are too 4. Boolean big to be represented by a normal JavaScript Number. 5. Undefined 6. Null 7. Symbol 8. Object Reference: https://www.w3schools.com/js/js_datatypes.asp ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 1. An object 2. An array 3. A date ©1992-2012 by Pearson Education, Inc. All Rights Reserved. // Numbers: let length = 16; let weight = 7.5; // Strings: let color = "Yellow"; let lastName = "Johnson"; // Booleans let x = true; let y = false; // Object: const person = {firstName:"John", lastName:"Doe"}; // Array object: const cars = ["Saab", "Volvo", "BMW"]; // Date object: const date = new Date("2022-03-25"); ©1992-2012 by Pearson Education, Inc. All Rights Reserved. FUNCTION ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces, or modules. This technique is called divide and conquer. This chapter describes many key features of JavaScript that facilitate the design, implementation, operation and maintenance of large scripts. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. You’ll combine new functions that you write with prepackaged functions and objects available in JavaScript The prepackaged functions that belong to JavaScript objects (such as Math.pow, introduced previously) are called methods. JavaScript provides several objects that have a rich collection of methods for performing common mathematical calculations, string manipulations, date and time manipulations, and manipulations of collections of data called arrays. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. You can define programmer-defined functions that perform specific tasks and use them at many points in a script ▪ The actual statements defining the function are written only once and are hidden from other functions Functions are invoked by writing the name of the function, followed by a left parenthesis, followed by a comma-separated list of zero or more arguments, followed by a right parenthesis maximum(value1,value2, value3) Methods are called in the same way as functions, but require the name of the object to which the method belongs and a dot preceding the method name Function (and method) arguments may be constants, variables or expressions ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Common analogy for this structure is the hierarchical form of management: A boss (the calling function, or caller) asks a worker (the called function) to perform a task and return (i.e., report back) the results when the task is done. The boss function does not know how the worker function performs its designated tasks. The worker may call other worker functions—the boss will be unaware of this. Figure 9.1 shows the boss function communicating with several worker functions in a hierarchical manner. Note that worker1 also acts as a “boss” function to worker4 and worker5, and worker4 and worker5 report back to worker1. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. return statement ▪ passes information from inside a function back to the point in the program where it was called A function must be called explicitly for the code in its body to execute The format of a function definition is function function-name( parameter-list ) { declarations and statements } ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Three ways to return control to the point at which a function was invoked ▪ Reaching the function-ending right brace ▪ Executing the statement return; ▪ Executing the statement “return expression;” to return the value of expression to the caller When a return statement executes, control returns immediately to the point at which the function was invoked ©1992-2012 by Pearson Education, Inc. All Rights Reserved. The script in our next example (Fig. 9.3) uses a programmer-defined function called maximum to determine and return the largest of three floating-point values. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. All variables declared with the keyword var in function definitions are local variables—this means that they can be accessed only in the function in which they’re defined. A function’s parameters are also considered to be local variables. There are several reasons for modularizing a program with functions. ▪ Divide-and-conquer approach makes program development more manageable. ▪ Software reusability. ▪ Avoid repeating code in a program. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. random method generates a floating-point value from 0.0 up to, but not including, 1.0 Random integers in a certain range can be generated by scaling and shifting the values returned by random, then using Math.floor to convert them to integers ▪ The scaling factor determines the size of the range (i.e. a scaling factor of 4 means four possible integers) ▪ The shift number is added to the result to determine where the range begins (i.e. shifting the numbers by 3 would give numbers between 3 and 7) Method Math.floor rounds its argument down to the closest integer ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Scaling Shifting ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Each identifier in a program has a scope The scope of an identifier for a variable or function is the portion of the program in which the identifier can be referenced Global variables or script-level variables are accessible in any part of a script and are said to have global scope ▪ Thus every function in the script can potentially use the variables ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Identifiers declared inside a function have function (or local) scope and can be used only in that function Function scope begins with the opening left brace ({) of the function in which the identifier is declared and ends at the terminating right brace (}) Local variables of a function and function parameters have function scope If a local variable in a function has the same name as a global variable, the global variable is “hidden” from the body of the function. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. JavaScript provides nine global functions as part of a Global object This object contains ▪ all the global variables in the script ▪ all the user-defined functions in the script ▪ all the built-in global functions listed in the following slide You do not need to use the Global object directly; JavaScript uses it for you ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Difference between var and let in JavaScript var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped. It can be said that a variable declared with var is defined throughout the program as compared to let. Variables declared by let have their scope in the block for which they are defined, as well as in any contained sub-blocks. In this way, let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function: UCCD 2323: Front-End Web Development JavaScript: Events In this chapter you will: ▪ Learn about the Document Object Model ▪ Learn about events ▪ Writing event handlers and handling the events The HTML DOM is a standard object model and programming interface for HTML. It defines: ▪ The HTML elements as objects ▪ The properties of all HTML elements ▪ The methods to access all HTML elements ▪ The events for all HTML elements The HTML DOM is a standard for how to get, change, add, or delete HTML elements. HTML DOM methods are actions you can perform (on HTML Elements). HTML DOM properties are values (of HTML Elements) that you can set or change. The HTML DOM can be accessed with JavaScript. In the DOM, all HTML elements are defined as objects. The programming interface is the properties and methods of each object. A property is a value that you can get or set (like changing the content of an HTML element). A method is an action you can do (like add or deleting an HTML element). Change the content of the element with id="demo“ using the innerHTML property. Output getElementById is a method, while innerHTML is a property. The getElementById method used id="demo" to find the element The innerHTML property is used to gett or replace the content of HTML elements Note: The innerHTML property can be used to get or change any HTML element, including and What are events? ▪ Events are actions or occurrences that happen in the system you are programming Example of events: ▪ user clicks a button on a webpage ▪ The user clicking the mouse over a certain element or hovering the cursor over a certain element. ▪ The user pressing a key on the keyboard. ▪ The user resizing or closing the browser window. ▪ A web page finishing loading. ▪ A form being submitted. ▪ A video being played, or paused, or finishing play. ▪ An error occurring. Need to respond to the events through the use of event handler ▪ Eg. Displaying an information box ▪ Need to register the event handler What is event handler? ▪ Event handler is a block of code (usually a JavaScript function that you as a programmer create) that will be run when the event fires What are event listeners? ▪ Event listeners listen for events ▪ The listener listens out for the event happening, and the handler is the code that is run in response to it happening. (html) (JavaScript) A reference to the button is atored inside a constant called btn using the Document.querySelector() function The “random” function returns a random number The btn constant points to a element Listening for the click event firing by setting the onclick event handler property to equal an anonymous function The code runs whenever the click event fires on the element, that is, whenever a user clicks on it. (1) Event handler properties (2) Inline event handlers — don't use these (3) addEventListener() and removeEventListener() In Eg1.html, the onclick property is the event handler property Setting the handler property to be equal to an anonymous function as in Eg1.html or to a named function name as in the example below: (html) (JavaScript) Explanation: ▪ The attribute value is literally the JavaScript code you want to run when the event occurs. This method is unmanageable and inefficient. With JavaScript, you could easily add an event handler function to all the buttons on the page no matter how many there were, using something like this: Method (1) Method (2) This is defined in is defined in the Document Object Model (DOM) Level 2 Events Specification The name of the event we want The code that to register this Example, comprises the handler for handler function ▪ (JavaScript) Can be used to register multiple handlers for the same listener. Note that it is perfectly appropriate to put all the code inside the addEventListener() function, in an anonymous function, like this: Example, ▪ (JavaScript) To remove a previously added listener, use removeEventListener() This allows you to have the same button performing different actions in different circumstances — all you have to do is add or remove event handlers as appropriate. Example, ▪ (JavaScript) To register multiple handlers for the same listener, ▪ Example, ▪ (JavaScript) ▪ The example below will not register both the handlers. The second line overwrites the value of onclick set by the first line Event handler properties have less power and options, but better cross-browser compatibility (being supported as far back as Internet Explorer 8). You should probably start with these as you are learning. DOM Level 2 Events (addEventListener(), etc.) are more powerful, but can also become more complex and are less well supported (supported as far back as Internet Explorer 9). You should also experiment with these, and aim to use them where possible. Event objects Preventing default behaviour Event bubbling and capture Event object is parameter specified with a name such as event, evt, or simply e in the event handler function. Their values are automatically passed to event handlers to provide extra features and information. Example ▪ (JavaScript) Explanation ▪ e.target refers to the button itself. ▪ The target property of the event object is always a reference to the element that the event has just occurred upon. ▪ In this example, a random background color is set on the button. Example 2 ▪ Select all elements using document.querySelectorAll(), then loop through each one, adding an onclick handler to each that makes it so that a random color is applied to each one when clicked. ▪ (JavaScript) Usage: ▪ prevent an event from doing what it does by default Example, ▪ Default behavior of a submit button is for the data to be submitted to a specified page on the server for processing, and the browser to be redirected to the page of some kind (or the same page, if another is not specified.) (HTML) (JavaScript) Explanation ▪ The code inside onsubmit event handler (the submit event is fired on a form when it is submitted) tests whether the text fields are empty. If they are, the preventDefault() function on the event object stops the form submission and then display an error message in the paragraph below our form to tell the user what's wrong. Output What happens in the capturing phase. ▪ The browser checks to see if the element's outer- most ancestor () has an onclick event handler registered on it in the capturing phase, and runs it if so. ▪ Then it moves on to the next element inside and does the same thing, then the next one, and so on until it reaches the element that was actually clicked on. What happens in the bubbling phase ▪ The browser checks to see if the element that was actually clicked on has an onclick event handler registered on it in the bubbling phase, and runs it if so. ▪ Then it moves on to the next immediate ancestor element and does the same thing, then the next one, and so on until it reaches the element. In modern browsers, by default, all event handlers are registered in the bubbling phase We can use the addEventListener(type, listener, useCapture) to register event handlers in the bubbling phase (default) or in the capturing phase. Example, Eg2.html ▪ (HTML) ▪ (CSS) ▪ (JavaScript) Explanation ▪ When the is clicked, the video is displayed, by changing the class attribute on the from hidden to showing ▪ When the video is clicked, it starts to play, but it causes the to also be hidden at the same time. This is because the video is inside the. Clicking on the video actually runs both the above event handlers. The standard Event object has a function available on it called stopPropagation() which, when invoked on a handler's event object, makes it so that first handler is run but the event doesn't bubble any further up the chain, so no more handlers will be run. (JavaScript) ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 2 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 3 In JavaScript, almost "everything" is an object. Booleans can be objects (if defined with the new keyword) Numbers can be objects (if defined with the new keyword) Strings can be objects (if defined with the new keyword) Dates are always objects Maths are always objects Regular expressions are always objects Arrays are always objects Functions are always objects Objects are always objects ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 4 JavaScript supports two kinds of objects 1) Intrinsic (or "built-in") objects, includes Array, Boolean, Date, Math and String. 2) User-define objects In JavaScript, almost "everything" is an object. Booleans can be objects (if defined with the new keyword) Numbers can be objects (if defined with the new keyword) Strings can be objects (if defined with the new keyword) Dates are always objects Maths are always objects Regular expressions are always objects Arrays are always objects Functions are always objects Objects ©1992-2012are always by Pearson objects Education, Inc. All Rights Reserved. 5 Source: www.w3schools.com Math object methods enable you to conveniently perform many common mathematical calculations. An object’s methods are called by writing the name of the object followed by a dot operator (.) and the name of the method e.g: Math.pow (2,3) In parentheses following the method name is are arguments to the method ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 6 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 7 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 8 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 9 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 10 Characters are the building blocks of JavaScript programs Every program is composed of a sequence of characters grouped together meaningfully that is interpreted by the computer as a series of instructions used to accomplish a task A string is a series of characters treated as a single unit A string may include letters, digits and various special characters, such as +, -, *, /, and $ JavaScript supports Unicode, which represents a large portion of the world’s languages String literals or string constants are written as a sequence of characters in double or single quotation marks ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 11 Combining strings is called concatenation ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 12 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 13 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 14 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 15 String method charAt ▪ Returns the character at a specific position ▪ Indices for the characters in a string start at 0 (the first character) and go up to (but do not include) the string’s length ▪ If the index is outside the bounds of the string, the method returns an empty string String method charCodeAt ▪ Returns the Unicode value of the character at a specific position ▪ If the index is outside the bounds of the string, the method returns NaN. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 16 String method fromCharCode ▪ Returns a string created from a series of Unicode values String method toLowerCase ▪ Returns the lowercase version of a string String method toUpperCase ▪ Returns the uppercase version of a string ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 17 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 18 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 19 String method indexOf ▪ Determines the location of the first occurrence of its argument in the string used to call the method ▪ If the substring is found, the index at which the first occurrence of the substring begins is returned; otherwise, -1 is returned ▪ Receives an optional second argument specifying the index from which to begin the search String method lastIndexOf ▪ Determines the location of the last occurrence of its argument in the string used to call the method ▪ If the substring is found, the index at which the last occurrence of the substring begins is returned; otherwise, -1 is returned ▪ Receives an optional second argument specifying the index from which to begin the search ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 20 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 21 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 22 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 23 Breaking a string into tokens is called tokenization Tokens are separated from one another by delimiters, typically white-space characters such as blank, tab, newline and carriage return ▪ Other characters may also be used as delimiters to separate tokens String method split ▪ Breaks a string into its component tokens ▪ Argument is the delimiter string ▪ Returns an array of strings containing the tokens String method substring ▪ Returns the substring from the starting index (its first argument) up to but not including the ending index (its second argument) ▪ If the ending index is greater than the length of the string, the substring returned includes the characters from the starting index to the end of the original string ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 24 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 25 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 26 delimiter string ▪ the string that determines the end of each token in the original string. The method returns the substring from the starting index (0 in this example) up to but not including the ending index (10 in this example). If the ending index is greater than the length of the string, the substring returned includes the characters from the starting index to the end of the original string. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 27 Date object provides methods for date and time manipulations ▪ Based either on the computer’s local time zone or on World Time Standard’s Coordinated Universal Time (abbreviated UTC) Most methods have a local time zone and a UTC version Empty parentheses after an object name indicate a call to the object’s constructor with no arguments ▪ A constructor is an initializer method for an object var d = new Date(); ▪ Called automatically when an object is allocated with new ▪ The Date constructor with no arguments initializes the Date object with the local computer’s current date and time ▪ A new Date object can be initialized by passing the number of milliseconds since midnight, January 1, 1970, to the Date constructor ▪ Can also create a new Date object by supplying arguments to the Date constructor for year, month, date, hours, minutes, seconds and milliseconds. Hours, minutes, seconds and milliseconds arguments are all optional If any one of these arguments is not specified, a zero is supplied in its place If an argument is specified, all arguments to its left must be specified var d = new Date(year, month, day, hours, minutes, seconds, milliseconds); 28 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 29 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 30 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 31 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 32 Date method parse ▪ Receives as its argument a string representing a date and time and returns the number of milliseconds between midnight, January 1, 1970, and the specified date and time var d = Date.parse("March 21, 2012"); Output : 1332259200000 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 33 Date method UTC ▪ Returns the number of milliseconds between midnight, January 1, 1970, and the date and time specified as its arguments ▪ Arguments include the required year, month and date, and the optional hours, minutes, seconds and milliseconds ▪ If an argument is not specified, a 0 is supplied in its place ▪ For hours, minutes and seconds, if the argument to the right of any of these arguments is specified, that argument must also be specified var d = Date.UTC(2012, 02, 30); Output : 1333065600000 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 34 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 35 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 36 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 37 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 38 ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 39 JavaScript is designed on a simple object- based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. Copyright © Pearson, Inc. 2013. All Rights Reserved. In JavaScript there are several ways to create a custom object. 1. Using the keyword new 2. Constructor function 3. Object Initializer/literal 3 Objects can be created with a new expression ▪ The most basic object is one that uses the Object constructor, as in var myObject = new Object(); The new object has no properties - a blank object 4 Properties can be added to any object, any time: var myAirplane = new Object(); myAirplane.make = "Cessna "; myAirplane.model = "Centurian"; The number of properties in a JavaScript object is dynamic Objects can be nested, so a property could be itself another object, created with new 5 Properties can be accessed in two ways: ▪ by dot notation var property1 = myAirplane.model; ▪ in array notation var property1 = myAirplane["model"]; var obj = new Object; obj[“prop”] = 42; => obj.prop obj[“0”] = “hello”; => obj If you try to access a property that does not exist, you get undefined 6 JavaScript constructors are special methods that create and initialize the properties for newly created objects When the constructor is called, this is a reference to the newly created object var kenscar = new Car('Nissan', '300ZX', 1992); A constructor is useful when you want to create multiple similar objects with the same properties and methods. It’s a convention to capitalize the name of constructors to distinguish them from regular functions. 7 For example, suppose you want to create an object type for cars. You want this type of object to be called Car, and you want it to have properties for make, model, and year. To do this, you would write the following function: function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } 8 Notice the use of this to assign values to the object's properties based on the values passed to the function. In JavaScript, the thing called this is the object that "owns" the code. The value of this, when used in an object, is the object itself. In a constructor function this does not have a value. It is a substitute for the new object. The value of this will become the new object when a new object is created. 9 Now you can create an object called mycar as follows: var kenscar = new Car('Nissan', '300ZX', 1992); var vpgscar = new Car('Mazda', 'Miata', 1990); Properties can be accessed : ▪ kenscar.make ▪ Kenscar[“make”] 10 An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). 11 The following example creates myHonda with three properties. Note that the engine property is also an object with its own properties. var myHonda = {color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}; Properties can be accessed : ▪ myHonda.color ▪ myHonda["color"] 12 var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; } }; Copyright © Pearson, Inc. 2013. All Rights Reserved. In a function definition, this refers to the "owner" of the function. In the example above, this is the person object that "owns" the fullName function. In other words, this.firstName means the firstName property of this object. Copyright © Pearson, Inc. 2013. All Rights Reserved. JavaScript methods are actions that can be performed on objects. A JavaScript method is a property containing a function definition. Copyright © Pearson, Inc. 2013. All Rights Reserved. You access an object method with the following syntax: objectName.methodName() You will typically describe fullName() as a method of the person object, and fullName as a property. The fullName property will execute (as a function) when it is invoked with (). This example accesses the fullName() method of a person object: name = person.fullName(); //John Doe Copyright © Pearson, Inc. 2013. All Rights Reserved. If you access the fullName property, without (), it will return the function definition: function () { return this.firstName + " " + this.lastName; } Copyright © Pearson, Inc. 2013. All Rights Reserved. The delete keyword deletes a property from an object: var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; delete person.age; // or delete person["age"]; 18 The delete keyword deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions. The delete operator should not be used on predefined JavaScript object properties. It can crash your application. 19 Copyright © Pearson, Inc. 2013. All Rights Reserved. JSON (JavaScript Object Notation) ▪ A simple way to represent JavaScript objects as strings ▪ introduced as an alternative to XML as a data-exchange technique JSON has gained acclaim due to its simple format, making objects easy to read, create and parse. Each JSON object is represented as a list of property names and values contained in curly braces, in the following format: { propertyName1 : value1, propertyName2 : value2 } Arrays are represented in JSON with square brackets in the following format: [ value0, value1, value2 ] Each value can be a string, a number, a JSON object, true, false or null. { "firstName": "John", "lastName": "Smith", "address": { "streetAddress": "21 Street", "city": "New York", "postal": 10021 }, "phoneNumbers": [ "212 555-1234", "646 555-4567" ] } ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 21 To appreciate the simplicity of JSON data, examine this representation of an array of address-book entries [ {'first': 'Cheryl', 'last': 'Black' }, {'first': 'James', 'last': 'Blue' }, {'first': 'Mike', 'last': 'Brown' }, {'first': 'Meg', 'last': 'Gold' } ] JSON provides a straightforward way to manipulate objects in JavaScript, and many other programming languages now support this format. In addition to simplifying object creation, JSON allows programs to easily extract data and efficiently transmit it across the Internet. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 22 Create a JavaScript string containing JSON syntax: var txt = '{ "employees" : [' + '{ "firstName":"John" , "lastName":"Doe" },' + '{ "firstName":"Anna" , "lastName":"Smith" },' + '{ "firstName":"Peter" , "lastName":"Jones" } ]}'; 23 Copyright © Pearson, Inc. 2013. All Rights Reserved. Since JSON syntax is a subset of JavaScript syntax, the JSON.parse can be used to convert a JSON text into a JavaScript object. var obj = JSON.parse(txt); 25 var txt = '{"employees":[' + '{"firstName":"John","lastName":"Doe" },' + '{"firstName":"Anna","lastName":"Smith" },' + '{"firstName":"Peter","lastName":"Jones" }]}'; var obj = JSON.parse(txt); for (var i=0; i < obj.employees.length; i++) { document.write(obj.employees[i].firstName + " " + obj.employees[i].lastName +""); } 26 Converts a JavaScript value to a JavaScript Object Notation (JSON) string. ▪ JSON.stringify(value [, replacer] [, space]) Parameters :- value ▪ Required. A JavaScript value, usually an object or array, to be converted. replacer ▪ Optional. A function or array that transforms the results. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 27 This example uses JSON.stringify to convert the contact object to JSON text. The memberfilter array is defined so that only the surname and phone members are converted. The firstname member is omitted. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 28 var contact = new Object(); contact.firstname = "Jesper"; contact.surname = "Aaberg"; contact.phone = ["555-0100", "555-0120"]; var jsonText = JSON.stringify(contact); document.write(jsonText); // Output: // { "firstname": "Jesper", "surname": "Aaberg", "phone": [ "555- 0100", "555-0120" ] } ©1992-2012 by Pearson Education, Inc. All Rights Reserved. 29 var contact = new Object(); contact.firstname = "Jesper"; contact.surname = "Aaberg"; contact.phone = ["555-0100", "555-0120"]; var memberfilter = new Array(); memberfilter = "surname"; memberfilter = "phone"; var jsonText = JSON.stringify(contact, memberfilter, "\t"); document.write(jsonText); // Output: // { "surname": "Aaberg", "phone": [ "555-0100", "555-0120" ] } Copyright © Pearson, Inc. 2013. All Rights Reserved.