JavaScript Notes

A page of nice to know JavaScript notes… (taken from the videos by Douglas Crockford)

If you have any tips or if there’s something I got wrong, feel free to tell me by leaving a comment!


Pre JavaScript 5

The for in problem

for (name in object) {
    if (object.hasOwnProperty(name)) { ... }
}
  • This only works if the object does not have a hasOwnProperty property
for (name in object) {
    if (Object.prototype.hasOwnProperty.call(object, name) { ... }
}
  • This will work for all

The trim() problem

if (typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function() {
        return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/,"$1");
    }
}
  • This will add the trim functionality to browsers that don’t have ECMAScript 5 standards implemented, which are IE8, Safari 4, and Konq 4.3

JavaScript 5

  • Use Object.create(parentClass, args) over the new keyword.
  • Keys must be strings
  • Extensible bit
    • Object.isExtensible(object)  – see if object is extensible
    • Object.preventExtensions(object) – one time method that will lock the object, it will be unable to take on new properties.
    • Object.seal(object) – changes all the object’s configurable bits
    • Object.freeze(object) – changes the object’s writable bits (makes it immutable)
  • Number has a max value of 9007199254740992
  • Flooring and other “non-common” arithmetic operations are in the Math object
  • Strings
    • Do not recognize surrogate pairs for unicode (beware when using substring functions)
    • Are immutable
    • Single quotes and double quotes work the same way
    • Can use === to check for same string
    • Multiline string literals are supported by the \ character. Make sure to not have any white space after the backslash.
    • String(num) will work even for null and undefined, num.toString() will not
    • Beware of parseInt to convert string into numbers (consider using the +str instead… num = +str)
      • Will parse till a non-digit character
      • parseInt(“12em”) === 12
      • parseInt(“08”) === 0
      • parseInt(“08”, 10) === 8 <- the 10 tells the function that it is radix(10)
    • now has a trim function on the String object
  • The supplant method which allows inserting data between {} based off a set of parameters – example(search for supplant)
    if (typeof String.prototype.supplant !== 'function') {
        String.prototype.supplant = function(o) {
            return this.replace(/{([^{}]*)}/g, function (a,b) {
                var r = o[b];
                return typeof r === 'string' ? r:a;
                })
        }
    }
  • <placeholder>

In General

  • (a + b) + c === a + (b + c)
    • Is not true if the integer is over the max value
    • if a,b,c are decimals (a = 0.1, b = 0.2, c = 0.3) the result is false
      • binary floating point storage is why it doesn’t work.
      • avoid problems by doing a multiplication to make them into integers
  • The NaN Problem
    • During mathematical calculations, NaN occurs as a result of undefined or erroneous operations. Can be hard to track down where the problem occurred.
    • NaN === NaN is false
    • Nan !== NaN is true
  • Arrays
    • Don’t need types or length specifications when declared
    • can add/extend an the array using myList[myList.length] = 'barley';
    • sort() actually sorts array values as if they were strings
    • Deleting elements should use array.splice(elementNumber, 1)
  • typeof function oddities
    • array returns ‘object’ <– can use Array.isArray() function instead
    • null returns ‘object’ <– this problem (clearly is wrong) stays in because it might break older programs
  • Falsy values
    • false
    • null
    • undefined
    • “” (empty string)
    • 0
    • NaN
  • Objects are mostly passed by reference
  • The === operator compares object references not values
  • Making sure strings are treated as ints
    • +”42″ is equal to 42
    • Number(“42”) is equal to 42
    • parseInt(“42”, 10) is equal to 42 <– a simple parseInt(“42”) would yield 4
    • so… +"3" + (+"4") = 7
  • The % is not modulo… it is a remainder operator. The difference occurs for negative numbers
    • -1 % 8 yields -1, not of 7
  • Pitfalls of type coercion
    • == and != use type coercion whereas === and !== do not
    • The follow are a list of “equalities” and should theoretically produce false because the left side is different from the right side
      • '' == '0'          // false
      • 0 == ''            // true
      • 0 == '0'           // true
      • false == 'false'   // false
      • false == '0'       // true
      • false == undefined // false
      • false == null      // false
      • null == undefined  // true
      • ' \t\r\n ' == 0    // true
  • !! produced booleans so !!234 yields true
  • Bitwise
    • /!\ There is a conversion from a 64-bit number into a 32-bit integer so large numbers might have problems
    • Operators &, |, ^, >>, >>>, <<
  • Switch/case statements
    • cases can be strings or expressions
    • behaves like C in that cases fall through to the next case if you don’t have break;
  • Standard JavaScript errors that you can catch from a try/catch statement
    • Error <- the generic one when none of the others fit
    • EvalError
    • RangeError
    • SyntaxError
    • TypeError
    • URIError
  • JavaScript scoping is based functionally and not by block. So nested for loops that both use an iterator variable “i” may have unexpected results
  • If there is no expression for a return statement, undefined is returned (unless it is a constructor in which case this is returned)
  • The arguments pseudo parameter
    • inside a function, arguments contain all the arguments passed in from the invocation
    • is an array-like object
    • has a length method that returns the number of arguments passed
    • in ECMAScript 5 convention, arguments inherits from Array.prototype making it essentially an array
  • The this pseudo parameter contains a reference to the object of invocation
  • Invocation
    • when there are too many arguments, the extra ones are ignored, the extras will still be stored in the arguments pseudo parameter
    • when there are too few arguments, missing values are filled with undefined
    • There is no implicit type checking on arguments
    • Function form
      • functionObect(arguments) <– like C function calls
      • this was set to the global object (prior to ES5/Strict)
      • this is set to undefined (post ES5/Strict)
    • Method form
      • thisObject.methodName(arguments)
      • thisObject[“methodName”](arguments)
      • this refers to thisObject
    • Constructor form
      • new FunctionObject(arguments)
      • this refers to the newly created object
    • Apply form
      • functionObject.apply(thisObject, [arguments])
      • functionObject.call(thisObject, argument)
      • this refers to thisObject
  • When doing DOM manipulations, for IE6 and IE7’s sake, if you remove nodes, make sure to remove any event handlers or risk memory leaks

Conventions

  • Identifiers start with lower case letters followed by zero or more letters, digits, _ or $
  • Constructor functions start with upper case
  • Starting with _ reserved for machines or implementations
  • $ should be reserved for machines
  • For comments, use mostly // because regular expressions often use /* or */
  • Douglas’ suggestions:
    • Avoid with statement, it’s not allowed in JavaScript Strict anyway
    • If you need to iterate through an array and order is important, do not use the for in loop, as it cannot guarantee the order
    • Declare all variables at the top of the function (kinda like C)
    • Declare all functions before you call them
    • Avoid messing/manipulating arguments directly
    • Don’t make functions in a loop
    • Be careful of using innerHTML properties, it can lead to cross-site scripting hacks
Advertisements

One thought on “JavaScript Notes

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Advertisements
%d bloggers like this: