Just started using jslint to check my javascript code. It indicated I should be replacing
result = value ? value : defaultValue;
with
result = value || defaultValue;
I thought this was a nice shortcut, and tried applying the principle to method calls on potentially null variables, so instead of:
if (arg) {
arg.doSomething();
}
I tried:
arg && arg.doSomething();
The latter works fine in the browser, but jslint complains with “Expected an assignment or function call and instead saw an expression.”
Is the last statement bad, wrong, dangerous, or is jslint being overprotective ? Using var dummy = arg && arg.doSomething(); do get the message to go away just seems silly.
JSLint should be considering this a warning at best (but then, JSLint doesn’t differentiate warnings from outright errors), definitely not an error — but remember that JSLint is about enforcing Crockford’s coding style standards, which may vary from yours (they certainly vary from mine); you might check out JSHint which offers more control, though I’m not immediately seeing an option for this specific condition.
Your
arg && arg.doSomething()is fine, but be aware that it’s somewhat advanced and you’ll lose some people doing maintenance on your code. I never use it in that way. I do use it in expressions, but not on its own. Whether you use it is up to you, but it’s not dangerous, just somewhat opaque.