Supplementary Materials Modern JavaScript 1
Modern JavaScript JavaScript is an essential component of HTML5 web applications Required by HTML5 application programming interfaces (APIs) Extends basic functionality of other HTML5 features Simulates HTML5 in older browsers Modern best practices promote more robust code Fewer errors Greater compatibility across browsers and devices 2
JavaScript Debugging Modern JavaScript development requires a debugger Greatly simplifies error detection and correction Most modern browsers have a debugger May be built-in or a plugin Quality varies We will use the Firebug debugger for Firefox Other browsers provide similar functionality 3
Firebug Firefox plug-in for debugging JavaScript code Downloaded and installed from getfirebug.com To launch, click the button in the toolbar (in some versions of Firefox, there is an icon in the bottom right corner of the window): Press <F12> to open and close Firebug using the keyboard Toolbar button Firebug Icon 4
Firebug Console Displays errors and warnings Allows entry of JavaScript commands Displays result Single-line mode: Provides IntelliSense/ command history (up arrow) Errors, warnings, and command results Single-line command entry Console button Minimize, Unpin, and Close buttons Switch to multi-line mode 5
Firebug Console (continued) Multi-line entry mode: Easier to see all typed code at once Multi-line command entry Run commands Switch to single-line mode 6
Object Literal Notation Defines objects and arrays dynamically Abbreviated syntax var CourseInfo = { subject: 'HTML5', code: 2320 }; // object var PrimeNumbers = [ 1, 3, 5, 7, 11 ]; // array alert( CourseInfo.subject ); alert( PrimeNumbers[0] ); 1. Launch Firefox and Firebug and switch to the console 2. Very carefully, enter the above code in the Firebug console Commands that do not return a value display the message undefined Do Now 3. Note the results in the alert() dialogs 4. Leave the Firebug console open; we will return to it shortly 7
Anonymous Functions Functions can be defined anonymously Without a name Also called inline or literal functions To invoke an anonymous function, assign it to a variable var MyFunc = function( val ) { alert('invoked with: '+val); }; MyFunc( 123 ); // displays 123 1. Very carefully, enter the above code in the Firebug console Be certain that you understand the alert() results Do Now 2. Leave the Firebug console open; we will return to it shortly 8
Anonymous Functions as Object Methods An anonymous function can be used as an object property The function becomes a method of the object var MyObj = { val: 123, method: function(){alert(this.val);} }; MyObj.method(); // displays 123 1. Very carefully, enter the above code in the Firebug console Be certain that you understand the alert() results Do Now 2. Leave the Firebug console open; we will return to it shortly 9
Functions as Parameters Many JavaScript functions take a function as a parameter The passed function provides additional behaviors Often after the primary function completes function primary( param ) { alert(1); param(2); } function secondary( value ) { alert(value); } primary( secondary ); 1. Very carefully, enter the above code in the Firebug console Be certain that you understand the alert() results 2. Leave the Firebug console open; we will return to it shortly Do Now 10
Anonymous Functions as Parameters An anonymous function can be passed as a parameter A function is a type of object Can be passed as data Avoids creating a global name for the function function first( second ) { alert('one'); second('two'); } first( function(v){ alert(v); } ); 1. Very carefully, enter the above code in the Firebug console Be certain that you understand the alert() results Do Now 11
Immediately Invoked Function Expression (IIFE) Anonymous function that is executed immediately after it is defined Pronounced iffy Also called self-executing function (misnomer) Used to encapsulate variables Benefits: Provides a safe scope Outside code cannot accidentally modify variables Creates a closure Event handlers within the IIFE can still access the variables later, even after the IIFE has finished executing Allows long variable names to be aliased Shorter names can be specified in the argument list 12
An IIFE Example IIFEs have an unusual syntax Function and call must be surrounded by parentheses Parameters can be passed to create local aliases var reallylongnamefromanotherlibrary = 123; Define the anonymous function (function( short ){ with argument named short var localvariable; // code using short and // localvariable goes here }( reallylongnamefromanotherlibrary )); Invoke the function immediately localvariable and short can only be accessed within the IIFE (and any nested functions) 13
Objects as Namespaces An object can be used as a namespace Encapsulates all global variables under a single name Reduces risk of variable name collisions var awesomelibrary = { author: 'John Doe', version: 1.0 }; (function(a){ alert('awesome Library '+a.version+' by '+a.author); }(awesomelibrary)); 14
Reducing Download Time JavaScript files are often minified Remove all comments, indentation, and line feeds Reduces file size to improve download time Minified libraries are often bundled together Multiple files can be concatenated into one Requires fewer connections May improve overall download time Some server preprocessors can do this automatically May also embed JavaScript files directly into the HTML Replacing external script elements with embedded code 15
Leading Semicolons Many developers begin each JavaScript file with a leading semicolon Helps prevent problems when minified files are concatenated If the first file is not properly terminated File #1 File #2 (does not follow best practices): (follows best practices): var x = 123; alert(x) Semicolon omitted Leading semicolon ;(function(){ var y = 456; alert(y); }()); Minified and concatenated result (syntax is correct): var x=123;alert(x);(function(){var y=456;alert(y);}()); Leading semicolon prevents statements from running together 16
Employing 1. Edit C:\course\misc\JavaScriptPractice\test.html 2. Locate the script elements in the head of this file Do Now What JavaScript files will be loaded? 3. Create a new JavaScript file that begins with a leading semicolon 4. Next, create an empty object literal, assigned to a global variable named MyCounter Refer to earlier slides if necessary If you get stuck, the solution is on the next slide 5. Add a version property, with a value of 1.0, inside the object literal 6. Add a count property, with a value of 0, to the object literal 17
Employing (continued) 7. Add a method named increment to the object literal The method should have a single argument named resulthandler The body of the method should increase the value of the count property by 1, then invoke the resulthandler, passing it count Your file should resemble the following: ;var mycounter = { version: 1.0, count: 0, increment: function(resulthandler) { this.count++; resulthandler(this.count); } }; 18
Employing (continued) 8. Save your work as C:\course\misc\JavaScriptPractice\my-counter.js 9. Create another new JavaScript file If you get stuck during the following steps, the solution is on the next slide 10. Begin the file with a leading semicolon, followed by an IFFE Pass mycounter as the value for an argument named mc 11. Within the IFFE, invoke mc s increment method, passing an empty anonymous function as the resulthandler 19
Employing (continued) 12. Immediately after the call to mc.increment(), call it again, passing another anonymous function 13. Give the new anonymous function a parameter named total 14. In the new function body, use alert() to display the value of total Your new file should resemble the following: ;(function(mc){ mc.increment( function(){} ); mc.increment( function(total){alert(total);} ); }(mycounter)); 15. Save your work as C:\course\misc\JavaScriptPractice\counter-test.js 20
Employing (continued) 16. Use any browser to display C:\course\misc\JavaScriptPractice\test.html What does the alert() display? Is this what you expected? Why or why not? The count property is incremented twice, and the dialog is only displayed by the second result handler Therefore, the value displayed should be 2 STOP 21