I remember reading some "funny" examples once of weird results JavaScript can give when you, for example, add strings to numbers etc. Does anyone have any good examples or a link to the blog that I might have read them on? Which ones are likely to catch a programmer out in the real world?
3 Answers
All the ones that are described in:
The biggest gotcha in JavaScript is that the == operation performs type type coercion and should almost always be avoided. Instead you should use the === to do a true boolean comparison.
For example, because of type coercion., 1 == true is true, but 1 === true is false. The == operator often hides type errors.
As a further illustration of true and false in this context these cases From Crockford's The Elements of JavaScript Style are illustrative.
'' == '0' // false 0 == '' // true 0 == '0' // truefalse == 'false' // false false == '0' // true
false == undefined // false false == null // false null == undefined // true
' \t\r\n ' == 0 // true
I would go get a copy of Douglas Crockford's Javascript the Good Parts. Its probably the best book on Javascript in terms of pointing out the parts of javascript that are good and those tha should be avoided at all costs.