Länk - Interesting list on pitfalls in javascript

published Oct 12, 2012 01:37   by admin ( last modified Oct 12, 2012 01:37 )

 jcampbelly:

  1. Try to forget the existence of "==" and use "===" instead. There are use cases for double-equals, but those are exceptions to the rule (usually cute hacks for brevity).
  2. Truthy and falsy values can be difficult to grasp. Falsy: "", 0, undefined, null, NaN (0/0). Truthy: "0", 1/0, {}.
  3. Type coercion is weird: (new Date() + 0) is ""Sat Oct 06 2012 12:56:45 GMT-0400 (Eastern Daylight Time)0"", (new Date() - 0) is 1349542608499. Incidentally, with implicit type coercion, the string form is local time and the numeric form is UTC.
  4. Always parse integers with a base: parseInt('07') is 7, parseInt('08') is 0, parseInt('08',10) is 8.
  5. Use console.log() instead of alert().
  6. Primitives are passed by value, objects are passed by reference.
  7. Declaring a variable without "var" makes it a global variable.
  8. object['property'] is identical to object.property except that "dot notation" cannot be used with language keywords (depends on browser) or numbers and bracket notation can be used with arbitrary strings (including spaces, for example).
  9. There is no scope inside of loops. Declaring a variable within a loop scope is the same as declaring it in the containing block. This can be hard to demonstrate, but take this very contrived example. The number "10" will be printed 10 times, because at the end of the loop execution there exists only one variable "i" whose value is 10, which is what the callback is referring to.

    for (var i = 0; i < 10; i++) {   setTimeout(function(){ console.log(i); }, 1000); } 



Read more: jcampbelly comments on In my first week of a JavaScript course -- Is there anything in particular I should watch out for that consistently trips up newcomers?