Notes about JavaScript with Doug Crockford

My notes while watching...

History of JavaScript with Doug Crockford JavaScript architect
  1. Part 1: 31 minutes
  2. Part 2: 31 minutes
  3. Part 3: 29 minutes
  4. Part 4: 20 minutes
  1. Eich wanted to do Scheme; told no by Netscape
  2. Netscape and Sun alliance - but Sun wanted Java to be in the browser
  3. ECMA language
JavaScript's key ideas
  1. load and go delivery - delivered as source (not binaries).
  2. loose typing - benefit in expressiveness, easier to write.
  3. objects are general containers (objects are hashtables - "brilliant")
  4. prototypal inheritance (objects inherit from objects without classes)
  5. lambda
  6. Linkage through global variables - a really bad idea (security, reliability issues)
Values
  1. number -
    1. internally 64 bit floating iee-754 "double"; only approximation (do arithmetic in whole numbers to avoid problems).
    2. NaN is a special number that's "toxic"; NaN != NaN. typeof NaN is number!
    3. Number() function produces NaN if has a problem; similar to + prefix operator
    4. parseInt(value, radix) - first digit 0 makes it think it's octal, so always include radix.
    5. Math object a mistake, but has useful functions on it.
  2. string -
    1. sequence of 0 or more 16 bit characters
    2. Encoded in UCS-2 not UTF-8. (no awareness of surrogate pairs)
    3. immutable - must make new strings
    4. no separate character time.
    5. can test with == (yay!)
    6. single and double quotes ' or "
    7. has a .length property - not the same as unicode character
    8. defines lots of useful methods
  3. booleans
    1. true and false
    2. Boolean function
    3. false: false, null, NaN, 0, "" [empty string]
    4. string 0 is true, string
  4. null
  5. undefined
    1. default value of parms and values
    2. confusing if a variable has
    3. extract a member that doesn't exist.
Dynamic Objects
  1. new Object() produces empty container of name value pairs.
  2. can access with dot or bracket
  3. no visible hash nature (JScript implemented with linked lists)
Loosely typed
  1. Not untyped - it's just loose.
  2. Syntacticly C, but it allows functions to be values.
  3. start with a letter or _ or $
  4. convention, vars, parms, members, functions start with lower case by convention
  5. initial underscore
  6. recommended to avoid $ for machine; _ for
  7. huge reserved words; also apply to member names
  8. // /**/ for comments
  9. + used for addition and concat (a mistake because loosely typed languages shouldn't have operator overloads
  10. == and != can do type conversion --- recommend that you do === and !== instead to avoid coercion; will run faster and more reliable. (Microsoft caused the reversal of this convention)
  11. && works oddly - if first operand is truthy, result is second operand else result is first operand. Common idiom for nullity check: return a && a.member;
  12. || can be used to set a default value - var foo = input || my_default;
  13. ! does what you expect
  14. !! produces a boolean :)
  15. bitwise & | >> <<- take floating point, turn into 32 bit integer, then turn it back into fp. Note that shifting in Javascript is slower than multiplying by 2.
Statements
  1. labeled breaks for loops
  2. for statemant
    1. special version for objects - for (var name in object){if object.hasOwnProperty(name){} //do something}. otherwise will go through all parent's keys as well.
  3. switch statment; switch value can be a number or a string; case values can be expressions. switch (express){case ';':case',";punctuation(); break;default:somethingElse();}
  4. exceptions: throw new Error(reason); or throw { name: exceptionName, message: reason} (that's an object literal)
  5. try/catch - only ever one catch clause, switch on name. Some built in exception names.
  6. with statement - ambiguous with global variables, don't use it. (5.20 into video 2)
  7. function name(parms){statments;}
  8. var name; var stuff = 0; if no initialization value, undefined.
  9. blocks don't have scope! different from C languages! only function scope! variable in a function visible everywhere in function. declaring a variable twice only makes it get created once.
  10. return. return expression; or return; if no expression, return value is undefined, except for constructors that return "this".
Objects
  1. Unordered collection of name/value pairs
  2. names are strings
  3. values can be any time incl other objects
  4. good for records and trees
  5. like a little database.
  6. object literal notation -
    1. can be used anywhere a value might appear
    2. : seperate name value, , seperates pairs. Note, don't leave trailing comma.
    3. names can be names or strings (optional quotes)
    4. myObject.name is the same as myObject['name']; (not quite the same 'cause you can have a reserved word in the second form!!! Ugh!)
    5. make a new empty object with var myObj = {};
    6. factory methods (makers) common idiom.
    7. tip: can use object parameters for "named parameters" including suitable defaults - think about replacing long list of parms with an object
  7. augmentation - can add new members by assignment.
  8. Linkage- objects can be created with a "secret link" to other objects - member search will fall back to the secret link. object(o) functions makes a new empty object with a link to object o. not used for storing - new members only add to primary member.
    1. var myNewObject(myOldObject); creates a "subclass". Note that assignment or "overriding" doesn't change the parent object - you create a copy of the member in the child class with a different value.
    2. simple: any object can inherit from older objects
  9. Prototypal inheritance
    1. js functions take the place of classes, methods, constructors, and modules!
    2. greater expressive power.
    3. sometimes deleting things makes them mutate (lets the parent object "shine through")
    4. only single inheritance
    5. all objects linked back to Object.prototype. but doesn't have any useful methods. no equals (contains the same stuff), or copy. but does have "hasOwnProperty".
  10. mark and sweep garbage collection
3 ways to create an object
  1. new Object()
  2. {} <-- preferred. (smallest most expressive)
  3. object(Object.prototype)
Objects passed by reference not by value. === compares references not object
delete statment.

Arrays
  1. Unusual because they inherit from Object
  2. indexes converted to strings and used as names for retrieving values
  3. efficient for sparse arrays (e.g. 1% population)
  4. not efficient for other cases
  5. good thing: no need to provide length or type on creation :)
  6. have length member - one higher than highest integer subscript (allows traditional for loop)
  7. literals [] myList =['ad','sdf','sf']; can append to it.
  8. dot notation cannot be used. use [] not new Array() to create a new array.
  9. inherits the array methods: concat, join, push, pop, slice, sort, splice
  10. delete array[number] removed item but leaves a hole. to remove hole use splice
    1. myArray = ['a','b','c','d']; delete myArray[1]; myArray.splice(1,1)
  11. linked to Array.prototype
How to decide between arrays and objects? use objects when names arb strings; arrays when seq integers.

How to decide if a value is an array or object? Two ways
  1. value.constructor === Array
  2. value instanceof Array
  3. niether work if value came from another frame. (omission in the language)
Cannot inherit from an Array - won't inherit length. You can still augment arrays. You can augment all arrays in the system by adding things to array.prototype.


Functions are first class objects.
  1. functions can be passed, returned stored as a value
  2. functions can inherit from Object (it can have methods!)
Function operator takes an optional name, parm list, block of stmts, and returns a func object. Can appear anywhere an expression can appear. Also call lambda.

function statement is shorthand for function assigned to a new var. e.g.
function foo{} is the same is var foo = function foo() {};
function names don't exist in a separate namespace.
can be defined inside of other functions.
inner function has access to the variables and parms of functions it's contained within (Static Scoping or Lexical Scoping) - got this right
  1. scope continues after the parent function returns.
  2. multiple calls to same function won't interact because local variables are renewed (see fade() example 3 - 5:30)
  3. first lambda language to go mainstream.
function in an object called "method".
function invocation

  1. called with too many objects, ignored
  2. too few objects, missing vals are undefined
  3. no type checking



  1. method form: myObject.methodName(args);
    1. get an extra parm called "this" set to myObject
    2. allows us to reuse functions on different objects - relies on invocation to know what object it's linked to.
  2. function form: functionObject(args)
    1. this is set to the global object -
    2. not useful because helper functions don't get to access the outer "this".
  3. Constructor form: new functionObject(args)
    1. new object created and assigned to "this"
    2. this will be returned if no explicit return value.
  4. functions get a special parm called "arguments" when invoked
    1. an array-like object (no array methods) containing all arguments
    2. has a length member
    3. good for functions that take variable number of parameters
Augmenting built-in types (append ".prototype" for the actual object name)
  1. Object
  2. Array
  3. Function
  4. Number
  5. String
  6. Boolean
typeof is broken: array returns it, so does null.

eval is the most misused feature of the language. don't use it. takes a string and compiles it. wastes time. reason they use it: don't know how to do subscript notation; . can use it with JSON - only when you can trust your server. use parseJSON method instead of eval. (The browser uses eval which is why it's there.)

Function function takes a string and compiles it - shouldn't be used in the same way eval shouldn't be used.

avoid new Boolean, new String, new Number because it's a vestigial remnant from Java. Particularly confusing with booleans - a new boolean is true.

3 - 19:45.

Make another object based on another object:
function object(o){
function F() {}
F.prototype = o;
return new F();
}

The global object is always there, but you can't name it or get to it. In browsers, window is the global object. (Browsers create a new object "window" and assign global to it.) Contains all global variables and prototypes.

Global variables are evil
  1. functions in an app can clobber
  2. cooperating apps clobber
  3. minimize it - mashups are going to fail.
  4. made much worse by the implied global - any var not declared is assumed to be global.
  5. jslint.com helps identify that sort of stuff. (doug wrote it)
Every object is a seperate namespace - declare a Yahoo object where everything else is contained within it. Have confidence that we reduce collisions with other scripts. Recommend all uppercase name. they have a registry to make sure no internal collisions occur.

Recommendation: use an anonymous function to wrap your application. take advantage of function scope to encapsulate state. Like this:

JAVAJOSH.WeBrowser = function() {
// define common vars
// define common funcs
return {
getNextPoser: function(cat, diff) {

},
showPoser: function () {
// I guess this is the entry point
}
};
}

} (); // the parens actually invoke this function

This is a "powerful platform on which to make our applications much more reliable".


Video 4
Type system -

Style
  • style isn't about personal taste
  • it's about rigor in expression
  • clearness in presentation
  • product adaptability & longevity
  • good rules keep quality high
  • critically important for JavaScript
  • the language is considered by some to be too soft - requires discipline for balance.
  • most JavaScript is crap
Conventions developed by Doug: http://javascript.crockford.com/code.html

Recommend: always use full forms including semi-colons. Why? Because when compiler sees an error it attempts to replace a nearby linefeed with a semicolon and try again, which can mask errors. Intentional error to make it easier for beginners.

Recommend: break line only after punctuation; don't break after name, string number, ) ] ++ --. Will help detect errors and avoid copy paste errors.

Recommend: avoid tricky expressions with comma operator ?. Avoid extra commas in array literals. It's bad because netscape and IE will report different lengths.

Always use blocks (e.g. in if statments). Only use blocks with structured statments. Define all variables at the top of the function (no advantage to defining at place of first use).

avoid falltrough switch

don't use assignment in condition of if and while. more likely you meant if (a == b)

be aware that == does type coercion. avoid if (a == null) but use if (!a) or if (a === null) [where else does this have an impact?]

never used javascript: as a label, or javascript in urls.

No comments: