In javascript pretty much everything is an object, so you'll be writing OO code even if you don't realize it. No escaping from OO, so it's better to embrace it from the beginning
Even for the simplest tasks, one good thing to do is to namespace your code. Let's say all you need is a function to validate a form, let's say you have a simple search box and you want to check if there's something typed in it before to send a request to your tired old server.
so you can easily do something like:
However, this is wrong on so many levels
First off, mixing content (HTML) and behavior (JS) is a no-no. All your JS code should be in a separate file and the markup should be clean and semantic. So slightly better example:
HTML:
JS:
Now, this can be improved and you can turn validate() into a reusable general-purpose validation function, but we're talking about the simplest scenario here and for the sake of the example we assume that this page will never get more complex than that (this never happens
)
What else is wrong here? Globals. We have a global 'myform' variable and a global validate() function. What can happen? Well, we start rotating ads using some ad provider which serves us random pieces of html. These ads also have scripts. Or, somewhere down the road you include a 3rd party widget of some sort and lo and behold, it comes with a javascript that has a function called validate(). Oops, naming collision.
To prevent such cases,
you should always start with namespacing your code.
This way you pollute the global namespace with only one variable, anything else you need, including other objects, functions and so on, you put as a property of your single global variable.
So, voila, here's an example how OO is the recommended way to go even for the simplest tasks. True, it may be just a little longer than the first example, but we get the benefits: namespacing, separation of concerns (content vs behavior) and maintainability/readability, since the first example is a little hard to read.