Semicolon insertion
- JavaScript helpfully (!) inserts semicolons when you forget
- Makes the language whitespace sensitive
- Lesson: use standard formatting
Generous operators
- Implicit type conversions
- Ignoring 'small' differences
Overloading of +
- Meaning of + depends on context
- Source of hard-to-track bugs
- Lesson: be careful, don't be clever
Strange Equalities
- The == operator is complicated, and not transitive
- (And for extra entertainment, remove the parens!)
- Lesson: use === and !== instead (try it!)
Special Values
- NaN and its properties
- The needless null
Not a number?
- NaN: a bad idea from IEEE 754
- Lesson: avoid it, especially comparisons
Null or undefined?
- Why null? Not clear
- Don't confuse with undefined
- In this code, should have used undefined
Truthiness
- Truthy and falsy values
- The troubles they cause
Truthiness
- Non-boolean values can be used in conditionals
- Truthy values are like true; falsy values are like false
- Lesson: use only booleans in boolean expressions
Prototypes
- No empty objects
- Problems with new & this
No empty objects
- No truly empty objects, due to prototype fields
- Entertaining example below by Doug Crockford
- Lesson: don't use objects as hash tables
Omitting new
- new allocates object & binds to this
- If omitted, this is bound to the global environment (!)
- Lesson: design constructors that don't use new
this and that
- The variable this is dynamically scoped
- Inside a function call o.f(), this is bound to o
- Lesson: avoid use of this; work around by defining that
Function declarations
- function f () {} short for var f = function () {}
- But not quite...
Silent Failure
- Examples of silent failure
- Strict mode
Silent Failure
- Illegal actions often have no effect in JavaScript
- Instead of complaining, interpreter just continues silently
- Violates principle of early errors
Strict mode
- A helpful hack to make JavaScript less generous
- Just put "use strict" as first line in script or function
- Turns some silent errors into thrown exceptions
- Disables some features (eg, eval)
- (Demo works in console but not live slide: not sure why)