This part one of a series of posts intended to clarify some confusing aspects of the language. This is not another tutorial.
So, what exactly is the purpose of this? What's with the fuss? Isn't JavaScript just another language? Well, yes but there are a few things which make it different from other languages. It has to run on the client's machine and yet not be an application means that it's important that we cover the possible variations (browser versions and types), while keeping an eye on size.
Size matters: smaller scripts mean faster loads, lower costs (less use of bandwidth) and ease of maintenance. But be careful: the smallest script is definitely not the easiest to maintain When writing JavaScript (and I'd say this about anything you write), keep in mind not only that it has to work. It's almost as important to consider that one day your code will have to be fixed or extended.
Aside from the obvious purpose of making it work, you should code for humans. The purpose of the syntax you choose should be so that it can be understood and maintained. Try to make it as eloquent as possible: short and clear. For example, what's best:
if (array) { ... }
if (array.length != 0) { ... }
if (array.length !== 0) { ... }
if (array.length) { ... }
While you think, enjoy this rant: A scripting language is all about abstractions. The further you go from, say, compiler code, the less lines of code it should take you to do something. With that in mind, a language like JavaScript should allow you to do what you want to do with very few lines of code. But what if your code is lengthy? Well, if it's not a framework, component or library, then your code is in dire need of one.
Time's up. Tally your results:
- No way! This is actually wrong! an empty array will evaluate to true, which is not what is intended here. More details on a later post.
- You're wasting precious characters.
- Nice try, but strict comparison doesn't change anything
- Right. In this case, we want to execute some code if the array is not empty. This is the best way to write it, because the
length
attribute will always return a number, and zero will be the same asfalse
here.
technorati tags:javascript
No comments:
Post a Comment