Dano Manion

JavaScript Notes

JavaScript Notes

Below is a some-what disorganized copy of my JavaScript notes. I do plan to organize these a bit better in the future so they can be more useful to others.

JavaScripts Many Benefits and Strengths

  • Both versatile and nearly ubiquitous: JS supports many paradigms including imperative, object oriented, and functional programming. There are also some unique qualities to the language such as being able to assign functions to variables. It also can be found on the client front-end side and back-end most commonly through Node.js.
  • Lightweight: can be executed locally without many or any communication with external servers.
  • Responsive UI (Rich Interfaces) while build-in to the browser: Since JS is so prevalent, we get the best of both worlds. A slick UI experience coupled with a clear and immediate interactivity. Unlike, Flash, Java Web Apps, Silverlight, Unity etc.
  • Prototypal Inheritance: Objects can inherit from other objects, which makes JS simple, powerful, and great for dynamic apps.

And Weaknesses

  • Security: Though common with any platform, JS ability to be executed from the browser adds a layer of potential vulnerability.
  • Ubiquitous and Versatility as a negative: because there are so many unique clients, from TV’s to a variety of web browsers, to the backend on a server. There are a lot of potential quirks can that can happen based of what level of ECMAScript standard that has been applied along with the fact that the interpreter may also contain bugs.

History

Influences

  • What other computer languages were an inspiration for JavaScript?
    1. Java - Syntax, conventions
    2. Self - Prototypal inheritance, dynamic objects
    3. Scheme - Objects as first-class values, loose typing
    4. Perl - Regular Expressions (terrible reg expressions)

Early History

  • At one point in history, LiveScript had server side capabilities, there was a <server> tag.
    • Someone did create a language called LiveScript that compiles to JavaScript. Just to confuse people I suppose 😜
  • JScript (Microsoft) and JavaScript (Netscape/Sun formally MCom) was actually the same thing. JavaScript was trademarked by Sun.
    • ECMAScript is the spec that JavaScript along with ActionScript and Nashorn (Java) uses
      • Used to mean European Computer Manufacturer Association, now it’s just a noun. Referred to as ES2, ES3, ES3.1, ES5, ES5.1, ES6, etc.
      • Max from Mindspace - “ES6 is the language and JavaScript can actually be considered more of a dialect.”
      • “JavaScript” could mean anything from the language as it exists in actual practice, to one vendor’s specific JavaScript engine.
      • “Harmony” features are a wish list of wanted features
      • Great Video with a Description of this
    • In 1997 the ECMA Spec was officially first defined.
    • Ended up with this interesting name because no one wanted to sign off on a standard and the eventually ended up at the European Computer Manufacturers Association for the standard, then they couldn’t come up with a name, thus ECMAScript (the working title) stuck
    • Netscape was created by Marc Andreesen (NCSA) & Jim Clark (SGI)
      • 1994 Netscape Navigator was released
      • Netscape contacted Brendan Eich in April of 1995 (Released Dec, 1995) to “create Scheme in the browser”
        • Brendan decides Java is not the language of the web, it’s way to complex for casual / “amateur” programmers
        • Wanted something forgiving for beginning programmers
        • Created in 10 days because of the short turn around time he needed to present it to his team
        • JavaScript was originally called “Mocha”, then “LiveScript” (for the “Live” brand, e.g. “LiveWire”), then finally “JavaScript”
      • Primitive Single Page Apps (SPAs) were also born at this time, although that name had not been given to them yet.
  • In JS 2007 became the most popular language in the world
  • JavaScript is the only programming language with built-in support in all major web browsers for client-side application scripting.* (At least ATM)

Terms

  • Browsers
    • Note: It’s best to check for features vs use of age of browsers.
      • This makes even more sense given the number of “Evergreen Browsers”
    • Modern Browsers: Newer then Ancient browsers.
      • Typically Chrome, Firefox and Safari.
      • Better dev tools and support many new specs
    • Evergreen Browsers: Browsers that continue to update themselves. The user never thinks about the version they are using because it just updates itself.
      • Chrome, Firefox, Safari, Opera, IE 10+ and Edge
    • Ancient Browsers (moving target): Browsers where the users have stopped using and/or companies have dropped support for them. Typically Mosaic, Netscape, IE 6,7, maybe 10.
      • slow and don’t support many of the modern APIs
    • Non-Browsers: JavaScript can run in the backend now vis-a-vis, Node.js
  • Web API: refers to all the JavaScript methods and objects that specifically allow developers to programmatically address and manipulate the browser
  • DOM (Document Object Model): a set of methods and objects used to represent an HTML document
  • DOM API: is a collection of other methods and functions available only in the browser environment but not directly related to HTML
    • Alt Image of the DOM
  • Shims & Polyfills (Regressive Libraries): small libraries that temporarily patch missing upcoming features that native browsers currently lack or implement on a non-specific way. The goal of these small libraries life is to be temporary as browsers adapt new these new features and APIs.
  • IIFE (Immediately Invoked Function Expression): is a way to wrap your code within a single function to control scope of your variables. Example of this. I’m sure we have all seen plenty of these ;)
  • Callback Functions - Functions that you send into other functions because the host function will callback to them.

Libraries

  • When Learning, the proper sequence is to:
    1. Learn JavaScript
    2. Learn the browser’s API
    3. Learn any new Library or Framework as Libraries like jQuery can actually become a crutch on your understanding of true Front-End development

ReactJS

-.

jQuery

  • jQuery: is can be seen as a wrapper around the DOM API (providing a level of abstraction) as-well-as … a collection of utility methods that aim to make solving common problems with JavaScript easier and more elegant across a wide range of browser.
    • One of the most popular JavaScript libraries in the world (…2017)
    • Beyond jQuery -“You don’t need jQuery anymore because the web API and JavaScript are sufficiently evolved such that a wrapper library can be omitted in favor of a closer-to-the-metal approach”
    • Many features jQuery added are now included natively in modern browsers
      • the ability to add, remove, and check for CSS classes as one example
        • add(), remove(), and contains() replaces addClass(), removeClass(), and hasClass()
    • ready() - has to wait too long (waits for all document elements to load) and can be perceived as slow to the user
    • CDN’s are good, but you give up control to a 3rd party that may not always be there.
      • Granted: most devs load one if CDN or the other else Local.
    • jQuery is good for unit tests though or any project that doesn’t need lightweight code

Frameworks

Webpack

General

What is JavaScript?

  • it is an Interpreted language and does not need a compiler.

JavaScript Tips

  • is a case sensitive language.
  • Load and go delivery
  • Objects as general containers
  • Objects are passed by Reference
    • Objects can be passed as arguments to functions, and can be returned by functions
    • Objects are not passed by value
  • Javascript does not care about whitespace. (Whitespace is used for readability)
  • Use camelCase for variables, functions and methods
  • Open curly braces on the same line
  • Define your functions before you call them
  • Always use semicolons to end a statement
  • Always use var (globally) or let (within scope) when declaring a variable
  • Work in ES5 Strict (past) & ES6 (now->future)
    • The plan for the language is that in the future strict mode will be the only one allowed
      • ES6 Modules are always in “strict” mode
      • Not every JS is created equal. Different browsers use different implementations of the spec.
      • "use strict"; disallows some of the more problematic or error-prone features of the full language.
        • One example is that with ES5, undeclared variables could be hoisted to the global scope
          • Be careful because this can be problematic when concatenation files.

              // Example inclusion in any program.
              "use strict";
            
              // Example of this use in a function
              function f(x) {
                  "use strict";
                  // ...
              }
            
  • Loosely Typed
    • JavaScript is untyped
    • Why is JS slow?
      • Any of these types can be stored in an variable, or passed as a parameter to any function

        	if (a = b) { ... }    	
        
        	// Does
        	a = b;
        	if (a) { ... }
        
        	// You may think it does
        	if (a === b) { ... }
        
  • The === is a “strict equality” or “triple equals” or “identity” operator compares object references. Does it have the same value & type?
  • Prototypal inheritance
  • Lambda - Functions as first-class objects
  • Linkage through global variables
  • Debuging no longer has to be done with alert("Hello, World!") calls and can now be done with console.log("Hello, World!")
  • When splitting code up, make sure you keep it the correct order.

Basic Syntax

Requesting Input

var name = prompt("What is your name?");
alert("Hello, " + name)
  • Identifiers start with a letter or _ or $
    • $ should be reserved for machines
    • Followed by zero or more letters, digits, _ or $
  • By convention, all variables, parameters, members, and function names start with lower case
  • Except for constructor functions which start with upper case
  • Initial _ should be reserved by implementations

  • ( parentheses )
    • Style note: No space between a function name and (
      • One space between all other names and ( Examples

          foo(bar);
          return (a+b);
          if (a=== 0) { ... }
          function foo (b) { ... }
          function (x) { ... }
        
  • [ brackets ]
  • { braces }

Where to bracket, on the right actually.

On the left ☹️ Will result in a Silent Error! Undefined.

return
{
	ok: false;
};

On the right 😊 Works well in JavaScript. It’s because the runtime could shove a semi-colon on the wrong line.

return {
	ok: true;
};

Comments

  • // - single line format (recommended)
  • /* */ - multiple line format

Variables

Variables are simply containers, we are going out to the computer memory and grabbing a little piece of it and giving it a name to use.

  • Variables not defined with var, let or const (keywords) are known as “Implied Variables”.
    • let is for block scoping, like within an if statement
      • Hoisting actually changes here where if let is declared after being called, will actually result in an error because unlike E5, let is not hoisted like var
    • const can’t be changed, write variables in ALL-CAPS
    • The drawback of this type of declaration is that these variables can actually be deleted
    • Example of this in action.
  • Defines variables within a function
  • Types are not specified
  • Initial values are optional
  • Only five primitive types are not objects: number, string, boolean, null, and undefined
    • the first three have corresponding object representation in the form of primitive wrappers
  • undefined is the default initial value
    • var name, var nrErrors = 0;, var a, b, c;, var a = 0, b = 0, c = 0;
  • Creating a variable
    • Examples:
      • var year;
      • var foo;
    • Characters Aloud
      • letters
      • numbers
      • _
      • $
    • var isn’t actually required, but recommended.
      • JavaScript will look for the variable if it cannot find it, it will simply create it.
    • The assignment operator
      • a = 5;
  • Escape character is “\

String Object

Scope & Variable Scope

Variables are only available within the code blocks (only functions) they are declared in.

Reserved Words

Hoisting

  • JavaScript treats all variable (Implied or Declared) as if they declared at the top of the function. Because of this it’s good practice to just do that, declare all your variables at the top of your function or program.
    • if a function, declare variables at the beginning of the function
    • if global, at the beginning of the code

Types of Variables

Numbers (Simple Type)
  • Only one number type, No Integers, 64-bit floating point
  • IEEE-754 (aka “Double” aka “Double Precision”)
  • Numbers are first class objects (not common in other languages)
    • A number can be:
      • stored in a variable
      • passed as a parameter
      • returned from a function
      • stored in an object
      • can have methods
  • Does not map well to common understanding of arithmetic
    • 0.1 + 0.2 !== 0.3?
    • Money has to be scaled in 100x then divided back
  • Associate Law does not hold. This is actually a common problem in computer arithmetic
    • Should work, but doesn’t
      • (a + b) + c === a + (b + c)
      • Produces false for some values of a, b c.
      • Integers under 900719254740992 (9 quadrillion) are ok.
  • Special number: Not a Number NaN
    • NaN === NaN is false!? ☹️ NaN is not equal to anything else
    • NaN != Nan is true!? ☹️ uhg!
  • parseInt function - Converts the value into a number
    • It stops at the first non-digit character
      • parseInt("12em") === 12
    • The radix (10) should always be used so we get the 0 in front of numbers otherwise parseInt will knock it off
      • parseInt("08") === 0
      • parseInt("08") === 8
  • Number(value) - Converts value into a number
  • Number literals, these are all the same
    • .01024e4
    • 1.024e+3
    • 10.24E2
  • Decimal fractions are approximate
    • a = 0.1; b = 0.2; // This is why it's so bad for finance
  • Math functions are in a Math objects rather then being methods of numbers, sadly borrwed from Java
    • floor most notable - integer
    • abs - absolute value
    • log - logarithm
    • max - maximum
    • pow - raise to a power
    • random - random number
    • round - nearest integer
    • sin - sine
    • sqrt - square root
  • Number methods
    • toExponential
    • toFixed
    • toLocalString
    • toPrecision
    • toString
    • valueOf
  • NaN
    • Special number: Not a Number
    • Toxic: any arithmetic operation with NaN as an input will have NaN as a result
    • NaN does not equal anything. NaN === NaN is false, NaN !== NaN is true
    • Infinity is a thing.
      • if you divide a number against 0, the program will actually return Infinity as a result.

          var x = 10, y = 0;
          (x / y) == Infinity // true
        
    • There is a Number Constructor. However, it makes this an Object. (see below)

        var x = new Number(234);
        x == 234 // true
        typeof x // 'object'
        x === 234 // false
      
Strings (Simple Type)

Nobody knows why they are called Strings

  • are a sequence of 0 or more 16-bit characters
  • UCS-2, not quite UTF-16 (This might have changed in ES6? I need to look this up.)
  • there is no seperator character type
    • characters are represented as strings with length of 1
  • Strings are immutable
  • Similar strings are equal (===)
  • "String" & 'String' are the same, no magic “quotes” / ‘quotes’ like in the now deprecated PHP 5.4.
  • Convention is:
    • Use " for external strings
    • Use ' for internal string and characters
  • String’s have properties and methods (behaviors)
    • charAt - single character in a string
    • concat
    • indexOf - Example of Extracting Items from a string and place them into an Array
    • lastIndexOf
    • match
    • replace
    • search
    • slice
    • split
    • substring
    • string.toLowerCase
    • string.toUpperCase();
    • string.length
    • string.indexOf("groovy"); find where ‘groovy’ is in a string
    • trim - added in ES5
    • and many, many more
    • Regular expressions
      • are terrible in JavaScript, very hard to read
      • = RegExp("hello"); or = /hello/
Boolean (Simple Type)

Beware of Boolean behavior.

  • Boolean(value)
    • returns false if value is false
      • false, null, undefined, "" (empty string), 0, NaN
    • returns true if value is true or simply exist
      • All other values (including all objects are true
        • “0” and “false” actually are true :/
    • Similar to !! prefix operator
    • Example of Booleans
    • A quick way to flip a Boolean is to set the current value with the NOT (!) operator

      //Flip Boolean bool = false; bool = !bool; // true

null
  • Not an object (most everything else is)
  • A value that isn’t anything
  • null === null = true;
undefined
  • This variable or thing doesn’t have a value set or doesn’t exist yet
  • Not an object (most everything else is)
  • if you create a variable but you don’t define it, it becomes undefined
  • A value that isn’t even that
    • The default value for variable and parameters
    • The value of missing member in objects
  • You could store undefined in an object

Arrays (aka Collections) (Complex Type)

Multiple Values

  • Javascript arrays are a type of object used for storing multiple values in a single variable. Each value gets a numeric index and may be any data type.
    • Arrays are Objects, Array inherits from Object
    • Each array has an index and value and is zero-based index.
  • E.g.: var myArray = [];
  • Supports mixed-data, which is not super common in other languages
  • Indexes are converted to strings and used as names for retrieving values
  • Very efficient for sparse arrays
  • Not very efficient in most other cases
  • One advantage: No need to provide a length or type when creating and array
  • Is actually a Object Type with additional features to make it more usable
  • Arrays have Methods

      var myArray = [10,20,"test",true,99]
      myArray.length
      myArray[myArray.length] = 'barley';
      myArray.reverse();
    
  • Is Array? Maybe this will work!

      Array.isArray([]); // true
    
  • Looping through an Array
    • Examples of Looping Through an Array

        // Safest for all version of JavaScript
        var i, s, myArray = ["One","Two","Three"], len = myArray.length;
      
        for (i=0; i<len; ++i) {
          if (i in myArray) {
            s = myArray[i];
            console.log("The value is: " + s);
          }
        }
      
        //  Douglas Crockford Example. He does not like `++` prefers `i += 1;`
        var d = 0, myDougArray = ["Un","Deux","Trois"];
      
        while (d < myDougArray.length) {
            console.log("The value in French is: " + myDougArray[d]);
            d += 1;
        }
      
  • Do not use for..in with arrays
  • More about Looping through Arrays
  • Use Objects for string to value pairs

Array Methods (built in functions)

  • concat, join, pop, push, slice, sort, splice
  • sort may give strange results because it uses Unicode point order to sort.
    • Example on how to fix this issue
    • & More info on sort

      var n = [4, 8, 15, 16, 23, 42]; n.sort(); // n is [15, 16, 23, 4, 42, 8]

      // Example of how sort orders Capitalized names vs unCapitalized names.sort(); // [ ‘Al’, ‘Bob’, ‘Maria’, ‘beatrice’, ‘marc’, ‘zimbu’ ]

  • delete will remove it but leave a hole. Use array.splice(number, 1)

      delete array[number] // removes the element but leaves a hole
      array.splice(number, 1) // removes the element and renumbers all the following elements
    
      myArray = ['a', 'b', 'c', 'd']
      myArray.splice(1,1); // ['a', 'c', d']
    

Arrays and Inheritance

  • Don’t use arrays as prototypes.
    • The object produced this way does not have array nature. It will inherit the array’s values and methods, but not its length
  • You can augment an individual array
    • Assign a method to it.
    • This works because arrays are objects
  • You can augment all arrays
    • Assign methods to Array.prototype

Object (Complex Type)

An object is a dynamic collection of properties.

  • In JavaScript Everything is an Object!
    • Arrays, functions, even numbers!
  • Objects could be considered “Associative Arrays” as in “String to Value”
    • Arrays are ordered number to value
  • Every property has a key string that is unique within that object
  • new Object() AKA “Object Literal” produces an empty container of name/value pairs
  • A name can be anything, a value can be any value except undefined
  • Members can be accessed with dot notation of subscript notation
  • No hash nature is visible (no hash codes or rehash methods)

2 Types of Objects

  • Native: Described in the ECMAScript standard
    • This can usually be tested by running the code in a none Host environment. Does it break? No, then all Native!
  • Host: defined in the host environment AKA the browser, example window and DOM objects

get, set and delete (3 operations)

dots and brackets interchangeable

  • get
    • object.name
    • object[expression]
  • set
    • object.name = value;
    • object[expression] = value;
  • delete
    • delete object.name
    • delete object[expression]

Class

  • It’s a blueprint, the definition, the description.
    • It’s a descriptor
    • In abstract
  • What does a class define?
    • Attributes: name, height, weight, gender, age
    • Behavior (Methods): walk, run, jump, speak, sleep

Objects - think of them of beling like little DBs

  • An Object is an unordered collection of name/value pairs
  • Names are strings
  • Values are any type, including other objects
  • Good for representing records and trees
  • Every object is a little database
  • Everything else is Objects
  • Objects can contain data and methods
  • Objects can inherit from other objects
  • The objected is created from the class.
    • Created based from the blueprint IE Class!
  • Object Linkage
  • Object can be passed as arguments to function, and can be returned by functions.
  • Delete operator can remove a property from an object
    • delete myObject[name];
  • Examples of Objects

      var myArray = [1,2,3,4,5];
      var myRE = /hello/;
      var myObject = {name: "Jack B. Nimble", 'goto': 'Jail', grade: 'A', level: 3};
    
      // With properties
      myArray.length
      console.log("How long is the Array?: " + myArray.length)
    
      // With methods
      console.log("Does the string contain \"Hello\"" + myRE.test("hello world"));
    
      var today = new Date();
      console.log("Today is: " + today);
    
      // Maker Function
      function maker(name, where, grade, level) {
          var it = {};
          it.name = name;
          it['goto'] = where;
          it.grade = grade;
          it.level = level;
          return it;
      }
    
      var myObject = maker("Jack", "Jail", "A", 3);
    
      console.log(myObject);
      console.log("Name: " myObject.name);
      console.log("Grade: " myObject.grade);
    
  • Examples of Primitives

      var myNumber = 123;
      var isValid = true;
    
  • You can create setters and getters on Objects

Global (Object)

  • sometimes points to, on browsers window is usually global

      var global = this;
    

Object Construction

  • Make a new empty object
  • All three of these expressions have exactly the same result:

    1. new Object()
    2. {} - the preferred form
    3. Object.create(Object.prototype)

Objects vs Arrays

  • Use objects when the names are arbitary strings
  • Use arrays when the names are sequential integeres
  • Don’t get confused by the term Associatvie Array, Object is the Associateive Array

Primitive

  • A JavaScript primitive is an instance of a particular data type, and there are five such in the language:
    1. String
    2. Number
    3. Boolean
    4. Null
    5. Undefined -
  • Examples of JavaScript primitives:
    • "This is a string"
    • null

Literal

  • A JavaScript literal represents a value of a specific type, such as a quoted string (String), floating-point number (Number), or boolean (Boolean)
    • "this is a string"
    • 1.45
    • true

Operators

  • Assignment Operator: =
  • Arithmetic Operators: +, -, *, /
    • uses operator precedence AKA order of operations 😊
  • Typof - typeof - works on everything but arrays and nulls
    • HOWEVER, for Arrays you can Distinguish them with this.
      • value.constructor === Array
      • value instanceof Array
    • Neither of these work when the value comes from a different frame.
    • ES5.1 we can use Array.isArray(value)
  • The remainder operator, not modulo operator!
    • % remainder takes the sign from the first argument not the second one, which modulo does
    • -1 % 8 // -1, not 7
  • Equal and not equal
    • use === and !=== as they do better with type coercion
  • Logical & or Guard Operator
    • &&
    • If first operand is true then result is second operand else result is first operand
    • It can be used to avoid null references

        if (a) {
            return a.member;
        } else {
            return a;
        }
      
    • can be written as return a && a.member
  • Logical OR AKA The default operator
    • ||
    • If first operand is true then result is first operand else result is second operand
    • It can be used to fill in default values. var last = input || nr_items;
      • If input is true, then last is inpute, otherwise set last to nr_items
    • May not work as expected if the first operand is a number, because 0 is false
  • Bang! Logical Not
    • !
    • If the operand is true, the result is false. Otherwise, the result is true
    • !! produces booleans
  • Bitwise
    • & | ^ >> >>> <<
    • The bitwise operators convert the operand to a 32-bit signed interger, and turn the result back into 64-bit floating point

Conditional Code

This is know as a “Code Block”

if ( condition ) {
	console.log("it's true!");
	// etc...
}

Typical comparison operators

  • Equality ==
  • Strict Equality AKA Idetntical === & !-- Not equal.
    • This does not do type corhistion so it presents the correct result
      • '' = '0' // false
      • 0 == '' // true but 0 === '' // false
  • Does not Equal !=
  • Greater then >
  • Greater then and Equal>=
  • Less then <
  • Less then and Equal<=

Logical AND / OR Operators

  • && - The guard operator, aka logical ‘and’
  • || - The default operator, aka logical ‘or’
  • Avoid Bitwise operators, they don’t do you any good in JS and are actually slower.

Eval (Never Us It)

  • eval(string)
  • The eval function compiles and executes a string and returns the result.
  • It is what the browser uses to convert strings into actions.
  • It is the most misused feature of the language.
  • Do not use it unless you really know what you are doing.

Statements

  • expression
  • if
  • switch
  • while
  • do
  • for
  • for in // for-in
  • break
  • continue
  • return
  • try/throw

Break Statements

Statements can have labels. Break statements can refer to those labels.

loop: for () {
	...
		if (...) {
			break loop;
		}
	...
}

For Statement

Iterate through all of the elements of an array:

See the Pen JavaScript: A Better Way To Iterate with For Loops by Dano Sketches (@DanoSketches) on CodePen.

Source

For-in Statement

Iterate through all of the members of an object.

for (var name in object) {
	if (object.hasOwnProperty(name)) {
		// within the loop,
		// name is the key of the current member
		// object[name] is the current value
	}
}

Switch Statements

Alternative to IF statements, esp. with lots of cases.

  • A Multiway branch.
  • The switch value does not need to be a number. It can be a sting.
  • The case values can be expressions.
  • Danger: Cases fall through to the next case unless a disruptive statement like break ends the case.

      switch ( value ) {
          case "Regular":
              alert();
              break;
          case "Premium":
              alert();
              break;
          default:
              alert();
      }
    

Without break you will get fall through.

Throw statment

  • you could throw anything you want, strings and objects too

      throw new Error(reason);
    
      throw {
          name: excpetionName,
          message: reason
      };
    

Try statement

  • You only get one catch clause
  • The JavaScript implementation can produce these exception names:
    • Error, EvalError, RangeError, SyntaxError, TypeError, URIError
    • No one seems to actually used these exception names however.

        try {
            ...
        } catch (e) {
            switch (e.name) {
                case 'Error':
                ...
                break;
            default:
                throw e;
            }
        }
      

With Statement (DON’T USE)

  • Intended as a convenient short-hand. It’s Ambiguous & Error-prione.

      with (o) {
          foo = kodal
      }
    

Function Statement

function name(parameters) {
	statements;
}

// jQuery example of an anonymous function with a callback $(“document”).ready(function() { $(‘div’).hover(function() { $(this).css(“color”, “black”); }, function() { // Callback - Functions that you send into other functions $(this).css(“color”, “yellow”); }) });

Return Statement

  • If there is no expression, then the return value is undefined.
  • Except for constructors, whose default return value is this

      return expression;
      or
      return;
    

Iteration (Creating Loops)

Programming ‘buzzword’ for a loop.

  • While Loop

      var a = 1;
      while ( a <= 10 ) {
          alert(a);
          a += 1;
      }
    
  • For Loop

      // setup index; check condition; increment index;
      for (var i = 1; i <= 10; i += 1) {
          alert(i);
      }
    
  • Do… While Loop - always happens at least once.

      var a = 1;
      do {
          a += 1;
      } while (a < 10);
    
  • Functionally with Map!

    • Example

      let a = rangeArray.map((x) => x.name);

Augmenting Built-in Types

  • Object.prototype
  • Array.prototype
  • Function.prototype
  • Number.prototype
  • String.prototype
  • Boolean.prototype

Trim (Example)

if (typeof String.prototype.trim !=== 'function') {
	String.prototype trim = function () {
		return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/,"$1");
	};
}

Persistence Support

Is not really built into JavaScript.

  • JavaScript lives in the browser and doesn’t really run I/O.
  • DOM (Document, Object, Model)
    • Document: is the page (web page)
    • Object: is the pieces
    • Model: What do we call these pieces? Data Model. Business Model. (agreed-upon set of terms)

Event Driven Programming

  • Event Handlers / Event Listeners : function waiting for an event to happen.
    • onload
    • onclick
    • onmouseover
    • etc

Event Propagation

  • When I child elements is clicked, a click event is fired and bubbles up the DOM tree, triggering each of its parent click event handlers.
  • All DOM elements have events
    • Mouse Events
    • Keyboard Events
    • Frame/Object Events
    • Form Events
    • Drag Events
    • Clipboard Events
    • Print Events
    • Media Events
    • Animation Events
    • Transition Events
    • Server-Sent Events
    • Misc Events
    • Touch Events
    • Event Object

Event Delegation

  • refers to the process of using event propagation (or Bubbling (like in ActionScript)) to handle events at a higher level in the DOM than on which event originated.
  • Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future. - JQuery.com

    // jQuery Example of adding the event listener to the parent while affecting the targeted li elements. // This is useful because li’s can be added post page load and still be used for triggering events $(‘ul’).on(“click”, “li”, function() { // do stuff });

  • Codepen.io Example

Syntax

  • element.event
    • window.onload
    • nameField.onblur
    • myelement.onclick

        myelement.onclick = function() {
            // My anonymous function.
            // This whole function is a statement.
        };
      

Debug

  • Syntax Errors: bad writing
  • Logic Errors:

Performance

  • Performance specific code is usually crufty
  • Clean code is easier to “reason about”.
  • Most of the code has a negligible impact on performance. Only optimize the code that is taking the time
  • Algorithm replacement is vastly more effective than code fiddling

Functions (Complex Type)

  • Breaking large chunks of code out to reusable bits.
  • JavaScript just has functions, other languages have methods, classes, constructors, modules, and other stuff

      // Show an Alert
      function showAlert() {			
          alert("Hello!")
      }
    
      showAlert();
    
      // Add two numbers.
      function addTwoNumbers(a,b) { // Parameter		
          var result = a + b;
          return result;
      }
    
      var x = addTwoNumbers(5,10); // Argument
      alert(x); // 15
    
  • You can write your functions in any order.
    • Javascript will scan your code first
    • Good practice to define your functions before you call them.
    • You can have as many functions as you want
  • Parameters
    • myFunction(a,b,c) {}
      • pass information to a, b, c.
    • Are not actually verified or validated. So you can call functions without arguments.
  • Arguments
    • myFunction(5,10,-200);
      • pass number ‘arguments’ to the parameters of the function.
  • Parameters and Arguments may seem interchangeable, but they are not.
  • return passing a result back
    • return is the last thing called, almost like break in a switch
  • Is actually a Object Type with additional features to make it more usable.

  • Another form of modularity

    • Immediately Invocable Function Expressions

        (function () {
            ...
        }()); // Neatness counts. Better style.
      
  • this: is a special keyword that refers to the object being referenced
    • by default this is the global object -> “window”: the top-level object which represents the document, location, history and a few other useful properties and methods
    • this remains the global object if you are calling a function
    • However, when calling an object constructor or any of its methods, this refers to the instance of the object
    • Example of how the this keyword scopes on Codepen.io

Function Expression

  • keyword: function
  • optional name
  • parameters
    • wrapped in parens ()
    • zero or more naees
    • separated by, (comma) (param1, param2)
  • body
    • wrapped in curly braces
    • zero or more statements
  • var statement
    • declares and initialized variables within a function
    • Types are not specified
    • A variable declared anywhere within a function is visible everywhere within the function
    • Further reading on Variable Scope

Function Statement

If the first token in a statement is function, then it is a function statement.

  • function
  • mandatory name
  • The function statement is a short-hand for a var statement with a function value
    • function foo() {}
      • expands to
        • var foo = function foo() {};
          • which further expands to
            • var foo = undefined;
            • foo = function foo() {};
              • the assignment of the function is also hoisted
  • Always Declare Variables in function otherwise they might become the global variable if it exist beforehand

      function showOrinaryPerson name() {
          var name = "Johnny" // Hoisted Here
          console.log(name);
      }
    
  • Two pseudo parameters
    • arguments
      • Code Example
      • When a function is invoked, in addition to its parameters, it also gets a special parameter called arguments
      • It contains all of the arguments from the invocation
      • It is an array-like object
      • arguments.length is the number of arguments passed
      • Weird interaction wtih parameters
      • If a function is called with too many args the extra args will be ignored
      • If a function is called with too few args they will be treated as undefined
    • this
      • The this parameter contains a reference to the object of invocation
      • this allows a method to know what object it is concerned with
      • this allows a single function object to service many objects
      • this is key to prototypal inheritance
  • Closure
    • Example
    • The context of an inner function includes the scope of the outer function
    • An inner function enjoys that context even after the parent functions have returned
    • Function scope works like block scope
      • the only scope in ES5 (non-struct) is function scope.
  • Treat the Function as Module

Function Examples

  1. Function that takes an argument and returns it
  2. Function that takes 2 numbers Added or Multiplied together
  3. Function that takes an argument and returns a Function
  4. Function that adds from two three invocations
    • Inovcation simply means running or calling a function done with parenthesis AKA Round Brackets.
  5. Function that takes a binary function, and makes it callable with two invocations
  6. Function that take a function and an argument, and returns a function that can supply a second argument
  7. Write methodize, a function that converts a binary function to a method.
  8. Write demethodize, a function that concerts a method to a binary function
  9. function twice that takes a binary function and returns a unary function that passes its argument to the binary function twice
  10. Write a function composeu that takes two unary functions and returns a unary function that calls them both
  11. JavaScript Write a function that allows another function to only be called once
  12. JavaScript Write a factory function that returns two functions that impletment an up/down counter
  13. Make a revocable function that takes a nice function, and returns a revoke function that denies access to the nice function, and an invoke function that can invoke a nice function until it is revoked

Higher Order Functions

  • Composition: functions that take functions as arguments
  • In JS, Functions are Values (this is not super common and is something special to JS)

List Transformations with Higher Order Functions

  • map: Transform a list into something into an Array of the same length but with each individual item transformed
  • filter: Transforms array into smaller array
  • find: Does the same thing as Filter but only returns the first item
  • reject: Does the same thing as Filter but inverted
  • reduce: the multi-tool of list Transformations

Methods

Which is actually a function? execCommand('Copy') - Copy data to clipboard.

Monads & Gonads

  • Github Snippet of a Monad from Douglas Crockford
  • Haskell and Category Theory
  • (Mt) -> (t M u) -> (M u)

      // All three functions return a monad.
      function unit(value)
      function bind(monad, function (value))
    
  • Axioms

      bind(unit(value), f) ==== f(value)
      bind(monad, unit) ==== monad
      bind(bind(monad, f), g)
                     ====
      bind(monad, function (value) {
          return bind(f(value), g);
      })       
    
  • The OO transform

      bind(monad, func)
      monad.bind(func)
    
  • Monad Thing - Macroid

Concurrency

  • Threads are evil!!!

Turn Based Processing

  • Single-threaded. Race free. Deadlock free.
  • The Law of Turns:
    • Never wait. Never block. Finish fast.
  • Events, Message passing. ~Threads. Mutexs.~
  • Web Browsers.
  • Most UI frameworks
  • Servers: Elko, Twisted, Nodejs
  • Asynchronicity can be hard to manage

Promises

  • Great Article about JavaScript Promises
  • Promises are an excellent mechanism for managing asynchronicity
  • A promise is an object that represents a possible future value
  • Every promise has a corresponding resolver that is ued to ultimately assign a value to the promise
  • A promise can have one of three states: ‘kept’, ‘broken’, or ‘pending
  • A promise is an event generator. It fires its event when the value of the promise is ultimately known.
  • At any time after making the promise, event handling functions can be registered with the promise, which will be called in order with the promise, which will be called in order with the promise’s value when it is known
  • A promise can accept functions that will be called with the value once the promise has been kept or broken
  • promise . when (success, failure) returns another promise for the result of your success function

  • Make a vow

      var my_vow = VOW.make();
          .keep(value)
          .break(reason)
          .promise
              .when(kept, broken)
    
  • Filesystem API

      read_file(name)
          .when(function success(string) {
              ...
          }, failure);
    

Exceptions

  • Exceptions modify the flow of control by unwinding the state
  • In a turn based system, the stack is empty at the end of every turn
  • Exceptions cannot be delivered accross turns
  • Broken promises can

Web API

Misc

Quotes

  • “‘JavaScript’ is not a language, but a whole world of decisions and use cases by now…” - Christian Heilmann
  • Programs are edited into existence. - Simon Allardice
  • Make your programs look like what they do.
  • Premature optimization is the root of all evil. - Donald Knuth
  • “When using ‘only’ libraries, “you are not a developer. You are, in fact, a library integrator” - Beyond jQuery by Ray Nicholus

Misc Code Examples

Leaders, Inventors and Influencers

Tools

  1. JSLint Check your code for the good parts
  2. JS.do - check your code!

Sources

  1. The Douglas Crockford JavaScript Master Class
  2. The JavaScript Cookbook, 2nd Edition
  3. JavaScript: the Good Parts
  4. JavaScript Variable Scope and Hoisting Explained
  5. JS.Next ES6/ES2015
  6. Mozilla JS Reference
  7. Advanced Javascript: Objects, Arrays, and Array-Like objects
  8. Beyond jQuery: by Ray Nicholus - Responsible for any “negative” tone around the jQuery library. How soon we forget how much it saved us in the recent-past.
  9. JavaScript is not the Enemy - Christian Heilmann
  10. What is this?