## Abstract

Notes on Douglas Crockford's Yahoo talk on Javascript

# Javascript

## Strings

• Strings are immutable
• Strings are objects and have methods

## Booleans

boolean(value) similar to !! prefix.

### Falsy Values

• false
• null
• undefined
• ""
• 0
• NaN

All other values (including objects are truthy):

• "false"
• "0"

## Values

• Null is a value that isn’t anything

### Undefined

• A value that isn’t even a value
• The default value for variables and parameters.
• The Value of missing members in Objects.

## Objects

• Unification of Object and Hashtable
• new object() produces an empty container of name/value pairs.
• A name can be any string, a value can be any value except undefined
• members can be accessed with dot notation or subscript notation
• No hash nature is visible (no hash codes or rehash methods) even though they behave that way

## Types

It is not untyped. It is loosely typed but it is very robust.

Functions can be values

## Identifiers

• Starts with a letter or _ or $ • Followed by zero or more letters, digits, _, or $
• By convention, all variables, parameters, members, and function names start with lower case.

• initial _ should be reserved for implementations

• \$ should be reserved for machines.

## Operators

+ used to concatenate as well as add. Also as a unary operator to convert string to number +"42" = 42. Or Number('42') = 42 Or parseInt("42", 10) = 42 or +“3” + (+“4”) = 7

Equal == and not equal != operators. Unfortunately these can do type coercion. Better to use === and !==.

&& “logical and operator” also known as the “gaurd operator” (28:25).

• if the first operand is truthy then result is second operand, else result is first operand
• it can be used to avoid null references
• console.log(a && a.m);

### || “logical OR” or “default operator”

• if first operand is truthy
• 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 truthy, then last is input. Otherwise set last to nr_items

### ! & !! Prefix logical not operator

• if the operand is truthy, the result is false. Otherwise the result is true.
• !! produces booleans.

### Bitwise operators

If you don’t intend for a bitwise operation, don’t use them.

## Statements

### Break

Labeled Break:

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


for arrays

### for in

For objects

Will also go through all the keys that the object inherits from (unfortunately).

To mitigate this you need to:

for (var name in object) {
if (object.hasOwnProperty(name)) { // this checks to see if the object actually has the property name.

}
}

• Do not use with arrays

### Switch

• Multiway Branch
• The switch value does not need to be a number, it can be a string.
• The case values can be expressions.

### Throw, try, catch

//constructor
throw new NameOfException(reason);

// or an object literal
throw {
name: exceptionName,
message: reason
}

try {
// code
} catch (e) {
switch (e.name)
}


• Error
• EvalError
• RangeError
• SyntaxError
• TypeError
• URIError

### with

• don’t use it

It uses constructs in which you can’t predict what the program will do

### var

• used for defining variables inside of a function

• Types are not specified

• initial values are optional. If you don’t give one it will be set to undefined

### Scope

• Blocks do not have scope
• only functions have scope
• vars defined in a function are not visible outside of the function
• js has implied globals
• If you don’t define a variable it is assumed that it is global.

### return

return expression;
return; //returns undefined except for constructors then the default value is this

• Every function will return a result. There is no void

## Objects

• Everything else is an object
• objects can contain data and methods
• objects can inherit from other objects

### Collections

• objects in js are collections
• 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

### Object Literals

• wrapped in {}
• Names can be names or strings
• values can be expressions
• : separates names and values
• , seperates pairs
• they can be anywhere a value can appear

### Maker function

function maker(name, where, grade, level) {
var it = {};  // make a new empty object
it.name = name;
it['goto']  = where;
it.level = level;
return it;
}

myObject = maker('Jack', 'jail', 'a', 3);


### Object Augmentation

• New members can be added to any object by simple assignment
• There is no need to define a new class

myObject.format.colorModel = ‘yCgCb’; myObject[name] = value;

• Objects can be created with a secret link to another object. (method by which inheritance is achieved)
• If an attempt to access a name fails, the secret linked object will be used.
• The secret link is not used when storing. New members are only added to the primary object.
• The object(o) function makes a new empty object with a link to object o. This is the basic operator for prototypal inheritance.
• a simple inheritance mechanism
• an object can inherit from an older object
• deleting a value in the child then allows request to shine through to the parent.

### Prototypal inheritance

• Some languages have classes, methods, constructors, and modules. JS’s functions do the work of all of these.
• Instead of Classical Inheritance, JS has Prototypal Inheritance.
• It accomplishes the same things but differently.
• it offers greater expressive power—but it’s different.
• Instead of organizing objects into rigid classes, new objects can be made similar to existing objects, and then customized.
• object customization is a lot less work than making a class, and less overhead too.
• One of the keys is the object(o) function. The other key is functions.

### Object Methods

• All objects are linked directly or indirectly to Object.prototype
• All objects inherit some basic methods—none of which are very useful
• hasOwnProperty(name) Is the name a true member of this object?
• No copy or equals method.

### Making a New Empty Object

All do the same thing:

new Object()

{} // prefered form

object(Object.prototype)


### Reference

• Objects can be passed as arguments to functions, and can be returned by functions.
• objects are passed by reference not by value
• The === compares object references, not values. true only if both operands are the same object

### Delete

Use to delete members from an object:

delete myObject[name]; // actually changes it to undefined


### Arrays

• inherits from Object
• Indexes are converted to strings and used as names for retrieving values.
• Very efficient for sparse arrays. For anything where memory tends to be linear, arrays are NOT your answer.
• Not very efficient in most other cases.
• One advantage: No need to provide a length or a type when creating an array.
• length member. It is always larger than the highest integer subscript. May not be the same as its actual length
• Do not use for in with arrays use for.

#### Literals

• use [] not new Array()
• Dot notation should not be used with arrays.
• New items can be appended: myList[myList.length] = ‘test’;

• concat
• join
• pop
• push
• slice
• sort
• splice

#### Deleting Elements

Removes the element, but leaves a hole in the numbering.

delete array[number]; // sets undefined for that index


Removes the element and renumbers all the following elements

array.splice(number, 1);


#### When to use

• Use objects when the names are arbitrary strings.
• Use arrays when the names are sequential integers.
• Don’t get confused by the term Associative Array. It means an object really.
• Gets linked to Array.prototype

#### Distinguishing Arrays

* Neither of these work when the value comes from a different frame.

value.constructor === Array

value instanceof Array


#### 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

• able to recieve any type of values and keys.

## Functions

• Are First Class Objects
• Can be passed, returned, and stored like any other value.
• functions inherit from Object and can store name/value pairs
• A function can contain other functions

• Can use this anywhere in the language where you can have an expression.

• It is really lambda

### Function Operator

function name(params) { //statements }

• the above is really just shorthand for var foo = function foo() {};

### Scope

• An inner function has access to the variables and parameters of functions that it is contained within.

• This is known as Static Scoping or Lexical Scoping.

#### Closure

• The scope that an inner function enjoys continues even after the parent functions have returned. This is called closure.

If you find yourself using more than a couple of parameters. Use an object or an object literal instead since they are much more forgiving, substitutions can be made dynamically, etc.

## MISC

### Garbage Collection

• mark and sweep