1. 1. What is JavaScript
    1. A short history
    2. JavaScript Implementations
      1. ECMAScript
        1. Not tied to host environment
          1. Web browser is just one host environment, tied to JavaScript but not ECMAScript
          2. Other host enviroments includes NodeJS, Adobe Flash, etc
          3. A host environment provides the base
          4. implementation of ECMAScript
          5. implementation of extensions designed to interface with the enviroment itself, e.g. DOM
        2. It describes the following parts of the language
          1. Syntax
          2. Types
          3. Statements
          4. Keywords
          5. Reserved words
          6. Operators
          7. Objects
        3. JavaScript implements ECMAScript, but so does Adobe ActionScript
        4. ECAMScript Editions
          1. Most recent edition: 5th for this book, 11st for now
          2. 1st edition
          3. basically JavaScript 1.1 but with ...
          4. browser-specific code removed
          5. unicode standard supported
          6. objects being platform-independent
          7. 2nd edition
          8. get into strict agreement with ISO/IEC-16262
          9. 3rd edition
          10. string handling
          11. definition of errors
          12. numeric outputs
          13. support for regular expressions
          14. new control statements, e.g. for, while...
          15. try-catch exception handling
          16. internationalization
          17. 4th edition
          18. big changes, defined an almost completely new language, was abondoned because of too big a jump
          19. 5th edition
          20. smaller change that could be implemented on top of existing JavaScript, won over the 4th edition
          21. published on December 3, 2009
          22. introduced addtional functionality
          23. native JSON object for parsing and serializing JSON data
          24. methods for inheritance and advanced property definition
          25. strict mode
        5. ECMAScript Conformance
          1. Support all "type, values, objects, properties, functions, and program syntax and semantics" as they are described in ECMA-262
          2. Support the unicode character standard
          3. Add "additional types, values, objects, properties, and functions" that are not specified in ECMA-262
          4. Support "program and regular expression syntax" that is not defined in ECMA-262
        6. ECMAScript support in web browsers
          1. Netscape3 + JavaScript 1.1
          2. IE3 + JScript 1.0
          3. Netscape4 + JavaScript 1.2
          4. IE4 + JScript 3.0
          5. Netscape 4.06 + JavaScript 1.3
          6. By 2008, the five major web browsers all complied with the 3rd edition
          7. IE8 was the first to start implementing the 5th edition and delivered the complete support in IE9
          8. Firefox 4 soon complied 5th edition
          9. compliant with 1st edition
          10. Not compliant with ECMA-262
          11. compliant with 5th edition
          12. compliant with 3rd edition
      2. Document Object Model (DOM)
        1. Definition
          1. The Document Object Model (DOM) is an application programming interface (API) for XML that was extended for use in HTML.
          2. XML: Carry or store data HTML: Display data
        2. Hierarchy
          1. <html> <head> <title>Sample Page</title> </head> <body> <p> Hello World!</p> </body> </html>
          2. Nodes can be removed, added, replaced, and modified easily by using DOM API
        3. Why DOM is necessary
          1. Netscape and Microsoft went separate ways in developing DHTML, if someone didn't rein in Netscape and Microsoft, the web would develop into two distinct factions
          2. It was then that the Wrold Wide Web Consortium (W3C) began working on the DOM
        4. DOM Level
          1. DOM Level 1
          2. became a W3C recommendation in 1998.10
          3. consisted of two modules
          4. DOM core
          5. provided a way to map the structure of an XML-based document
          6. allowed for easy access to and manipulation of any part of a document
          7. DOM HTML
          8. extended the DOM core
          9. added HTML-specific objects and methods
          10. DOM Level2
          11. consisted of
          12. DOM views
          13. Describes interfaces to keep track of the various views of a document https://www.w3.org/TR/2000/REC-DOM-Level-2-Views-20001113/views.html
          14. DOM events
          15. Describes interfaces for events and event handling
          16. DOM style
          17. Describes interfaces to deal with CSS-based styling of elements
          18. DOM traversal and range
          19. Describes interfaces to traverse and manipulate a document tree
          20. DOM Level3
          21. consisted of
          22. methods to load and save documents in a uniform way (DOM Load and Save)
          23. methods to validate a document (DOM Validation)
          24. support all of XML 1.0, including XML infoset, XPath, and XML Base
          25. DOM4
          26. Presently the W3C no longer maintains the DOM as a set of levels, but rather as the DOM Living Standard, snapshots of which termed DOM4
          27. added Mutation Observers to replace Mutation Events
          28. Other DOMs
          29. several other languages have had their own DOM standards
          30. Scalable Vector Graphics (SVG) 1.0
          31. Mathematical Markup Language (MathML) 1.0
          32. Synchronized Multimedia Integration Language (SMIL)
          33. standard recommendations from W3C
          34. some other languages have developed their own DOM implementation
          35. Mozilla's XML User Interface Language (XUL)
        5. DOM support in Web browsers
          1. IE made its first attempt with version 5
          2. IE implemented most of DOM Level 1 with version 5.5
          3. IE9+ supported all DOM levels
          4. Netscape started supporting DOM with Netscape 6 (Mozilla 0.6.0)
          5. After Netscape 7, Mozilla switched its efforts to the Firefox browser
          6. Firefox 3+ supports all of Level 1, nearly all of Level 2, and some parts of Level 3
          7. Now, all of the major browsers have supported all DOM standards
      3. Browser Object Model (BOM)
        1. IE3 and Netscape3 featured a browser object model that allowed access and manipuation of the browser window
        2. It was the only part of a JavaScript implementation that had no related standard
          1. There are some de facto standards, such as window and navigator object, but each browser defines its own properties and methods
          2. Thanks to HTML5, which codified much of the BOM as part of a formal specification
        3. BOM deals with
          1. browser window
          2. browser frames
          3. In the context of a web browser, a frame is a part of a web page or browser window which displays content independent of its container, with the ability to load content independently.
          4. any browser-specific extension to Javascript
          5. pop up new browser windows
          6. move, resize, and close browser windows
          7. the navigator object
          8. provides detailed information about the browser
          9. the location object
          10. gives detailed information about the page page loaded in the browser
          11. the screen object
          12. gives detailed information about the user's screen resolution
          13. the performance object
          14. gives detailed info about the browser's memory consumption, navigational behaviour, and timing statistics
          15. support for cookies
          16. costom objects
          17. XMLHttpRequest
          18. Internet Explorer's ActiveXObject
    3. JavaScript Versions
      1. Mozilla, as a descendant from the original Netscape, is the only browser vendor that has continued the original JavaScript version numbering sequence
      2. Most browsers talk about JavaScript support in relation to their level of ECMAScript compliance and DOM support
        1. e.g. https://www.w3schools.com/js/js_versions.asp
  2. 2. JavaScript in HTML
    1. The <Script> element
      1. Intro
        1. Primary method of inserting JavaScript into an HTML page
        2. Created by Natscape and first implemented in Netscape navigator 2
        3. 7 attributes
          1. async
          2. optional
          3. indicates that the script should begin downloading immediately but should not prevent other actions on the page
          4. valid only for external script files
          5. charset
          6. optional
          7. the character set of the code specified using the src attribute
          8. <script charset="UTF-8" src="demo_script_charset.js"> http://a4esl.org/c/charset.html
          9. rarely used because most browsers don't honor its value
          10. crossorigin
          11. optional
          12. configures the CORS settings for the associated request, by default CORS is not used at all
          13. crossorigin="anonymous" will not set the credentials flag
          14. crossorgin="use-credentials" will set the credential flag, meaning the outgoing request will include credentials
          15. defer
          16. optional
          17. indicates that the execution of the script can safely be deferred until after the document's content has been completely parsed and displayed
          18. valid only for external scripts
          19. IE 7 and earlier also allow for inline scripts
          20. integrity
          21. optional
          22. allows for verification of Subresource Integrity (SRI) by checking the retrieved resource against a provided cryptographic signature.
          23. useful for ensuring that a Content Delivery Network is not serving malicious payloads
          24. language (deprecated)
          25. src
          26. optional
          27. indicates an external file that contains code to be executed
          28. type
          29. optional
          30. replaces language
          31. indicates the MIME type
          32. application/x-javascript
        4. 2 ways to use <script>
          1. embed directly into the page
          2. You cannot have "</script>" anywhere in the code
          3. <script> function sayScript() { console.log("</script>"); } </script> Above will cause an error
          4. <script> function sayScript() { console.log("<\/script>"); } </script> Ok to use with escaping character
          5. include from an external file
          6. <script src="example.js"></script>
          7. .js extension is not required, which open the possibility of dynamically generating JavaScript code using a server-side scripting language, or for in-browser transpilation into Javascript from a JavaScript extension language such as TypeScript or JSX
          8. Servers often use the file extension to determine the MIME type, so be sure to double-check it is returning the correct MIME type
          9. should not include inline script otherwise will be ignored
          10. There is also some time taken to download the file
          11. Processing of the page is halted while the external file is interpreted
        5. Script src supports JavaScript file outside the domain
          1. <script src="http://www.somewhere.com/afile.js"></script>
          2. It will send a GET request to get a file
          3. This initial request is not subject to the browser's cross-origin restriction, but any JavaScript returned and executed will be
          4. Make sure you are the domain owner or the external domain is owned by a trusted source
        6. Order of multiple script elements
          1. From top to bottom, the above one must be completedly interpreted before the second
          2. async and defer can change the order
      2. Tag Placement
        1. Traditionally was placed within the <head> element on a page
          1. <!DOCTYPE html> <html> <head> <title>Example HTML Page</title> <script src="example1.js"></script> <script src="example2.js"></script> </head> <body> <!-- content here --> </body> </html>
          2. Main purpose was to keep both CSS and JS files in the same area
          3. However, JS code will be downloaded, parsed, and interpreted before the page begin rendering, thus causing a noticeable delay before page rendering (people will see blank page)
        2. Modern webs includes all JS references before </body>
          1. <!DOCTYPE html> <html> <head> <title>Example HTML Page</title> </head> <body> <!-- content here --> <script src="example1.js"></script> <script src="example2.js"></script> </body> </html>
          2. Page is rendered before JS processing, reducing the time on blank page
      3. Deferred scripts
        1. <!DOCTYPE html> <html> <head> <title>Example HTML Page</title> <script defer src="example1.js"></script> <script defer src="example2.js"></script> </head> <body> <!-- content here -->
        2. Signals the browser to begin downloading immediately but execution should be deferred after the entire page has been parsed
        3. The HTML5 specification indicates that scripts will be executed in the order in which they appear, and will execute before the DOMContentLoaded event
        4. In reality, though, deferred scripts don't always execute in order or before the DOMContentLoaded event, so it's best to include just one when possible.
        5. Not work for inline script
          1. except IE 4-7
        6. Support begin with IE4, Firefox3.5, Safari 5, Chrome 7, other browsers will simply ignore this attribute. So it is still best to put deferred scripts at the bottom of the page
      4. Asynchronous scripts
        1. <!DOCTYPE html> <html> <head> <title>Example HTML Page</title> <script async src="example1.js"></script> <script async src="example2.js"></script> </head> <body> <!-- content here --> </body> </html>
        2. Signals the browser to begin downloading files immediately, but not guarantees the order of execution in which they are specified.
        3. Make sure there are no dependencies between the files, and files are not modifying DOM as they are loading
        4. Guaranteed to execute before the page's load event, and may execute before or after DOMContentLoaded
        5. not use document.write
      5. Dynamic script loading
        1. let script = document.createElement('script'); script.src = 'gibberish.js'; script.async = false; document.head.appendChild(script);
          1. By default, scripts created in this fashion are async, but since not all browsers support async, we should set async to false to unify behaviour.
          2. However, this can severely damage performance since resources fetched in this fashion will be hidden from browser preloaders.
          3. To inform preloaders, you can explicitly declare the link in the document head
          4. <link rel="subresource" href="gibberish.js">
      6. Changes in XHTML
        1. XHTML is a stricter, more XML-based version of HTML
        2. In XHTML, the <script> element requires that you specify the type attribute as text/javascript.
        3. <script type="text/javascript"> function compare(a, b) { if (a<b) { console.log("A is less than B"); } else if (a>b) { console.log("A is greater than B"); } else { console.log("A is equal to B"); } } </script>
          1. <b is invalid in XHTML since it is interpreted as the beginning of a tag
          2. Two solutions
          3. Replace < with &lt; --------------------------------- if (a&lt;b) { console.log("A is less than B"); }
          4. Wrap in a CDATA --------------------------------- <script type="text/javascript"> //<![CDATA[ function compare(a, b) { if (a < b) { console.log("A is less than B"); } else if (a> b) { console.log("A is greater than B"); } else { console.log("A is equal to B"); } } //]]> </script>
          5. Many browsers (non XHMTL-compliant) don't support CDATA section so CDATA markup must be offset by JS comments
      7. Deprecated Syntax
        1. Unless you are using XHTML or the <script> tags for non-JavaScript, the best practice is to not specify a type since MIME type are not standardized across browser
        2. <script><!-- function sayHi(){ console.log("Hi!"); } //--></script>
          1. Hide embedded JS code from the browser that didn't support it
          2. Not needed any more for modern browsers
    2. Inline code v.s. External files
      1. Best practice is to use external files
        1. Maintainability
        2. Caching
          1. Browsers cache all JS files according to specific settings. If two pages are using the same file, the files is downloaded only once.
        3. Future-proof
          1. No need to use XHTML comment hacks
    3. Document modes
      1. Introduced by IE5.5
      2. modes
        1. quirks
          1. Make IE behave if it were IE 5 with several nonstandard feature
          2. Triggered by omitting the doctypes
        2. standards
          1. Make IE behave in a more standards-compliant way
          2. Triggered by using doctypes
          3. <!-- HTML 4.01 Strict --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <!-- XHTML 1.0 Strict --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- HTML5 --> <!DOCTYPE html>
        3. almost standards
          1. has a lot of the features of standards mode but isn't as strict
          2. Treatment of spacing around images, especially in tables
          3. Triggered by transitional and frameset doctypes
          4. <!-- HTML 4.01 Transitional --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- HTML 4.01 Frameset --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> <!-- XHTML 1.0 Transitional --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- XHTML 1.0 Frameset --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
    4. The <noscript> element
      1. Disable JavaScript
      2. Content contained in it will be displayed
        1. When the browser doesn't support scripting
        2. When the browser's scripting support is turned off
      3. Can contain any HTML elements except for <script>
      4. <!DOCTYPE html> <html> <head> <title>Example HTML Page</title> <script ""defer="defer" src="example1.js"></script> <script ""defer="defer" src="example2.js"></script> </head> <body> <noscript> <p>This page requires a JavaScript-enabled browser.</p> </noscript> </body> </html>
  3. 3. Language Basics
    1. Intro
      1. Based primarily on ECMAScript 6th edition
    2. Syntax
      1. Everything is case-sensitive
      2. Identifiers
        1. First character must be a letter, _, or $
        2. All others may be letters, _, $, or numbers
        3. Letters in an identifier may include extended ASCII or Unicode letter characters such as À and Æ, not recommended
        4. By convention camel case
      3. Comments
        1. // or /* xxx */
      4. Strict mode
        1. Strict mode is a different parsing and execution model for JavaScript, where some of the erratic behavior of ECMAScript 3 is addressed and errors are thrown for unsafe activities.
        2. You can use it at the top of a script or specify in a function
          1. function doSomething() { "use strict"; // function body }
      5. Statements
        1. Terminated by a semicolon ; (not required but best practice)
        2. Alway use {} for if (not required for one line statement but best practice is to always have it)
    3. Keywords and reserved words
      1. Current reserved
        1. break do in typeof case else instanceof var catch export new void class extends return while const finally super with continue for switch yield debugger function this default if throw delete import try
      2. Future reserved
        1. Always reserved: enum
        2. Reserved in strict mode
          1. implements package public interface protected static let private
        3. Reserved in module code
          1. await
    4. Variables
      1. loosely typed, meaning that variable can hold any type of data
      2. var
        1. undefined if declare without initialization
        2. Using var to define a variable makes it local to the function scope
          1. function test() { var message = "hi"; // local variable } test(); console.log(message); // error!
        3. Define a variable globally by omitting var
          1. function test() { message = "hi"; // global variable } test(); console.log(message); // "hi"
          2. Not recommended, hard to maintain, strict mode will throws a ReferenceError
        4. var hoisting
          1. function foo() { console.log(age); var age = 26; } foo(); // undefined
          2. = function foo() { var age; console.log(age); age = 26; } foo(); // undefined
      3. let (introduced in ECMA 6)
        1. similar to var except that let is block scoped, var is function scoped
          1. if (true) { var name = 'Matt'; console.log(name); // Matt } console.log(name); // Matt if (true) { let age = 26; console.log(age); // 26 } console.log(age); // ReferenceError: age is not defined
        2. does not allow for any redundant declarations within a block scope
          1. var name; var name; let age; let age; // SyntaxError; identifier 'age' has already been declared
        3. does not support hoisting
          1. // name is hoisted console.log(name); // undefined var name = 'Matt'; // age is not hoisted console.log(age); // ReferenceError: age is not defined (refered as temporal dead zone) let age = 26;
        4. when using let in the global context, it will not attach to the window object as they do with var
          1. var name = 'Matt'; console.log(window.name); // 'Matt' let age = 26; console.log(window.age); // undefined
          2. Persis for the lifetime of the page
        5. conditional declaration
          1. <script> var name = 'Nicholas'; let age = 26; </script> <script> // Suppose this script is unsure about what has already been declared in the page. // It will assume variables have not been declared. var name = 'Matt'; // No problems here, since this will be handled as a single hoisted declaration. // There is no need to check if it was previously declared. let age = 36; // This will throw an error when 'age' has already been declared. </script>
          2. try (age) { // If age is not declared, this will throw an error } catch(error) { let age; } // 'age' is restricted to the catch {} block scope
        6. loop
          1. for (var i = 0; i < 5; ++i) { setTimeout(() => console.log(i), 0) } // You might expect this to console.log 0, 1, 2, 3, 4 // It will actually console.log 5, 5, 5, 5, 5
          2. for (let i = 0; i < 5; ++i) { setTimeout(() => console.log(i), 0) } // console.logs 0, 1, 2, 3, 4
      4. const (introduced in ECMA 6)
        1. Similar to let exception that it must be initialized with a value, and that value cannot be redefined after declaration
          1. const age = 26; age = 36; // TypeError: assignment to a constant
          2. // const still disallows redundant declaration const name = 'Matt'; const name = 'Nicholas'; // SyntaxError
          3. // const is still scoped to blocks const name = 'Matt'; if (true) { const name = 'Nicholas'; } console.log(name); // Matt
          4. const person = {}; person.name = 'Matt'; // ok
          5. for (const i = 0; i < 10; ++i) {} // TypeError: assignment to constant variable
          6. let i = 0; for (const j = 7; i < 5; ++i) { console.log(j); } // 7, 7, 7, 7, 7 for (const key in {a: 1, b: 2}) { console.log(key); } // a, b for (const value of [1,2,3,4,5]) { console.log(value); } // 1, 2, 3, 4, 5
      5. Best practices
        1. Don't use var
        2. Prefer const over let if not reassign
    5. Data types
      1. primitive type
        1. undefined
        2. null
        3. boolean
        4. number
        5. string
        6. symbol
          1. newly introduced in ECMAScript 6
      2. complex data type
        1. Object
      3. The typeof operator
        1. let message = "some string"; console.log(typeof message); // "string" console.log(typeof(message)); // "string"
    6. Operators
    7. Statements
    8. Functions