Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

&& for null safe method invocation, good or bad?

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.

like image 716
andypandy Avatar asked Jun 17 '26 15:06

andypandy


1 Answers

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.

like image 162
T.J. Crowder Avatar answered Jun 20 '26 03:06

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!