Notes on Crockford's Javascript Video Lecture 2
Notes I took while watching the second video of Douglas Crockford’s JavaScript lecture
Statements
JavaScript has all the statements that you’d expect to find in any of the other C langauges. e.g. if, switch, while, do, for, break, continue, return, try/throw; but there are some differences in how they are used.
You can label loops and then break out of them by label. Handy if you want to break out of a nest of loops.
The for statement can loop through an array and through the members of objects.
Unfortunately for looping through an object will take you through all the kys of all the objects that the object inherits from. To prevent this you have to test that the object being looped through itself has that property. This is highly recommended to avoid strange behavior.
Switch values don’t need to be numbers, can be strings
Case values can be expressions – handy
You have to explicitly terminate case clauses, as usual.
Switch statements allow a default case.
Throwing exceptions behaves typically, as does try/catch.
You can generate exception objects by calling its new constructor, or use with object literal
JavaScript comes with the following exceptions:- Error
- EvalError
- RangeError
- SyntaxError
- TypeError
- URIError
You can, of course, make up your own exceptions.
Avoid using the with statement. It was designed to be a convience for dealing with objects, but there is an error in its design leading to ambiguous statements.
There is a function statement used for declaring functions.
The var statement defines variables within functions. JavaScript is loosely typed so you just declare the variable and optionally initialize.
Without initialization variables are undefined.
Unless you limit the variable scope with var they are assumed to be global. :-/
Unlike most C languages, blocks do not have scope. There is only function scope.
Return can return an expression or just return;
return; doesn’t return nothing, it returns undef
When used in constructors they will return the new object.
Objects
Objects contain data and methods.
Objects only inherit from other objects, there is no concept of a Class.
Objects in JavaScript are an unordered collection of name/value pairs. Names are strings, values are anything including other objects or expressions.
Every object is essentially a tiny database
Object Literals
Object Literals are an easy way of creating a new object. The are data wrapped in { }. ”:” separates names and values. ”,” separates pairs. An object literal can be used anywhere a value can appear.
Object Literal Example: var myObject = {firstName: “Stephen”, ‘lastName’:’Ball’, middleInitial:’A’, age: 29};
// These syntaxes are interchangable
var theName = myObject.firstName;
var destination = myObject['firstName'];
Maker functions can be used to build objects. Pass material to maker function and it will make an object and return it
Object Literals can have nested objects, or object literals, as values.
If we pass an object literal to a function, the function doesn’t know if the object already existed or was a literal declared with the call.
Rather than define a function that takes a lot of parameters (e.g. more than two or three), think about passing an object instead.
Objects in JavaScript can be augmented at anytime with new methods and data. There is no class, so obviously no need to define a new one. Just modify the object you want to expand directly.
// to add data to an object simply set it
existingObject[newKey] = newValue;
existingObject.newKey = newValue;
Object Linkage
When objects are created they have a secret link to another object. This is how inheritance is achived.
If a member is requested from an object and the object doesn’t have it, JavaScript silently follows the link to the secret object and sees if it has the member and, if so, returns it. The child object now has the data member locally. Odd side effect: if you delete a data member of a child object that is set in the parent object then the child object’s data isn’t really deleted. If requested the “deleted” data will be fetched from the parent object again without notice.
The secret link is not used for storing new values in the parent object. Data is only retreived.
Obviously this means that there is only single inheritence in JavaScript. Also that there is truly no Class equivalent in JavaScript. Objects only inhereit from objects.
We can use the object function to make a new empty object that has that linkage to an existing object. ex: var myNewObject = object(myOldObject);
Some languages have classes, methods, constructors, modules: JavaScript has functions, and functions do the work of all of those. This allows greater expressive power, but requires a different way of thinking.
There is garbage collection in JavaScript.
All objects are linked directly or indirectly to Object.prototype that has some basic methods, but no copy method and no comparison method.
You can see if two objects are, in fact, the same object; but not tell whether they are equivilent.
Object Construction
There are three ways to create a new, empty object:- new Object{}
- {}
- object(Object.prototype)
All three return exactly the same object, {} is recommended for conciseness.
Objects can be passed to functions as arguments and returned from fucntions.
Objects are always are passed by reference.
=== between objects will only return true if both objects are the same object.
The delete operator will remove members from objects, delete myObj[key] by changing the value to undefined.
Arrays
Arrays are unusual:- array inherits from object
- array indexes are converted into strings and then used as names for retrieving values
- very efficient for sparse arrays, but not for everything else
- arrays aren’t typed
- arrays have length member, it is always 1 larger than the highest integer subscript which may not be its actual length (!)
- it does allow a for loop to go through the array easily by just saying less than array.length
- do not use for…in with arrays
Array Literals
- uses []
- can contain any number of expressions
- new items can be appended, arr[arr.length] = value
- can’t use dot notation with arrays, subscript notation instead
- [] is the preferred method to create a new array, not the new array construct
Array Methods
- concat
- join
- pop
- push
- slice
- sort
- splice
Deleting from array: delete array[number] removes element but leaves a “hole” in the array as an undefined value. To completely delete a value and index you need to splice it out.
Use Object or Array?
Since objects and arrays are so similar, when do you use which?
Use objects when names are arbitrary strings, e.g. associative array.
Use arrays when names need to be sequential.
Arrays all inherit from array.prototype.
If you get a value, there are two methods to tell whether it is an array or an object:- value.constructor === Array
- value instanceof Array
BUT neither of those methods work when value comes from a different frame, a bug in the language.
You can’t inherit from an array because the value produced will be an object, not an array. You can augment an individual array by adding methods to it. You can also assign methods directly to Array.prototype to change all arrays in the program.
Leave a Comment