Besides main languages features like prototype inheritance, anonymous function and closures, there is many little things that makes me like programming with JavaScript more than other popular languages, server or client side.
Most languages implements these basic features, but I like how JavaScript implement them more in terms of readability and flexibility.
First the ternary operations
variable = (condition)? true: false;
They are nice because JavaScript doesn't care much about white spaces and breaklines so I can use them even with long parameters:
variable = (condition)
? some.long.method.name()
: some.other.long.method.name();
But most of the time I'll opt for a simple conditional assignation, I find them easier to read than ternary operations
link = a.href || 'http://www.google.com';
Cute, but if a is undefined it will raise an error. That's when && becomes handful. I don't think it can totally replace the ternary syntax but it's handy in many cases.
link = a && a.href || 'http://www.google.com';
link = (a)? h.ref: 'http://www.google.com';
Object chaining is also a great feature that jQuery take advantage elegantly
$('.someclass')
.find('a')
.addClass('someclass')
.end()
.show();
I really like how you can play with functions and arguments. I find myself using apply quite often, it's useful to be able to specify the scope of function manually and be able to pass it variable length arguments
alert.apply(window, ['Hello world']);
Dealing with variable argument is quite easy too since they are stored in a predefined variable
function test() {
alert(arguments[0]);
}
Things I miss (not all basic features):
Yeah I was that bored ..
@Archatas
Well I admit that I only tested it on IE6+, FF2+ (and Epiphany) and Opera. But I picked this trick while learning jQuery so I guess that it's somewhat safe to use.
Seems like every time they add something to JS it starts acting more like Perl - and that's a good thing.
Native JSON decode - if it's coming from a trusted source, then 'eval' works nicely :) JSON encode does seems like an obvious thing that's missing though.
Is that
<code class="javascript"> obj .SomeMethod(param) .SomeOtherMethod(param2); </code>
supported in all modern browsers?
Or is it better to use something like
<code class="javascript"> obj.someMethod( param ).someOtherMethod( param2 ); </code>
?
permalink Archatas ~ February 22, 2008 at 3:14 p.m.