Originally posted on 2015–10–31 on http://steveltn.me.
Recently I read about JavaScript Garden, and took some (extremely brief) notes.
Objects
- Everything is an object, except for
null
andundefined
. Object.delete
deletes a key.{ k: v }
and{ 'k': v }
are equivalent.
Prototypes
- Instances do not have prototypes by default, their constructors do.
- Prototype should be an instance, instead of constructors.
in
andfor in
both traverse the prototype chain.
this
- There are five scenarios.
Constructor
this
refers to the new object.
Scope
- There is no block scope
foo = 42
defines global variable;var foo = 42
defines scope variable.- Only function arguments and variables defined by
var
are scope variables. var
andfunction
statement will be moved to the top of their enclosing scope.
Arrays
- Don’t use
for in
because it traverses the prototype chain. Usefor
instead. - You can truncate arrays by assigning
length
property. new Array()
is broken. Use[1, 2, 3]
instead.
Types
==
is broken, it coerces types.===
doesn't.==
and===
compares identity instead of equality, when either side of it is an object.typeof
andinstanceof
are broken.- The correct way of getting an object’s class is by using
Object.prototype.toString
. - The only use of
typeof
is to check if a variable is defined. - The only use of
instanceof
is to deal with custom made objects that originate from the same JavaScript context - JavaScript will apply type coercion wherever possible.
Core
- The scope of
eval
is broken. setTimeout
andsetInterval
callseval
internally, if the arguments are strings.- You can override the global variable
undefined
. - JavaScript could guess wrong when automatically inserting semicolons.
delete
doesn't work whenDontDelete
attribute is set, hence can only be used to delete properties explicitly set on normal objects.
setTimeout
and setInterval
- The timeout and interval are inaccurate.
this
in the callback refers to the global objectsetInterval
can be blocked, causing function calls stacking. You can usesetTimeout
and set new timeouts in the callback instead.