Javascript quirks and scope
Though i like to think that i am quite adept at javascript understanding sometimes i forget the quirks it has.
Just today i was programming and wanted to call a simple function editPost, then when testing what i wrote i get an error saying "editPost is not function", damn i said to myself thinking that i mistyped somewhere, but as it turned out i used editPost as a global variable in another function, there i forgot to add the 'var' and it became global. I think its a common mistake and sometimes its hard to maintain such code especially when working on bigger projects witch has lots of javascript lines. Sure there are methods to solve scope problems like namespacing, using OOP programming style in general, but you must apply these methods early in development in order to escape the mess later. Here's a simple example of my problem that i had:
function getPost(){
editPost = 'not used'; //no 'var' means the variable is global scope; this type of variable is called implied global
...
return post;
}
function editPost(id){
...
//browser will shout an error, that "editPost is not a function
...
}There is a good book about these kind of quirks that Javascript has i recommend you reading it if you are interested, its called "JavaScript: The Good Parts" written by Douglas Crockford. It's a small book, but informative and explains javascripts buggy parts like:
'' == '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
and many other awful and beautiful features of javascript insight-fully.