Thursday, August 19, 2010

There is an Order to Things, and you Missed it

When evaluating a condition in JavaScript, the conditions work from left to right, so the following bit of code is completely worthless.

if (someobj.someproperty && someobj) {

The && condition will only proceed to check the next condition if the condition directly before it returned true. In this case 'someobj' must exist before the property 'someproperty' can be read, therefore the final check to see if 'someobj' exists will only be reached if a property of that object exist - at this point it is already assumed that 'someobj' exists. I think I just talked myself into a circle there.

Entirely worthless. There, I said it again.

Friday, July 16, 2010

A String is Not an Array You Lazy Bastard

This one kills me, taking a String and treating it like an Array. How many times have you seen this stupid bit of coding lazyness?

$(this).val().length;

Or another one of my favorites:

$(this).val()[3];

Unless jQuery's val method magically somehow returns an array, your fucking doing it wrong.

This is a String, if you want to use it like an Array, then make it into an Array first. It's easy:

$(this).val().split("")[3];

Now that will work across all browsers, and its way less ambiguous.

We could also use the JavaScript charAt method to do the same thing:

$(this).val().charAt(3);

Which also makes your intentions obvious.