Expressions in JavaScript Ternary Operator and JSLint

James Wiseman picture James Wiseman · Jun 6, 2011 · Viewed 8.9k times · Source

I recently received a comment on one of my blog posts about JSLint asking why JSLint threw an error with the following:

s === "test" ? MyFunc() : MyFunc2();

The error generated was:

"Expected an assignment or function call and instead saw an expression."

Clearly JSLint is expecting an assignment here, somthing more like:

var y = (s === "test") ? MyFunc() : MyFunc2();

But, I don't really see the problem with the first example. Is it really the case that ternary operators should only be used for assignments?

I couldn't see anything on JSLint.com, nor was there anything apparent in the book JavaScript: The Good Parts. And, the same error is also reported in the community fork JSHint.

Anyone?

Answer

Raynos picture Raynos · Jun 6, 2011

It's an expression. It's equivalent to writing

0 === 1;

You're writing an expression that has immediate side effects and that's considered bad.

Generally expressions are useless statements that have no side effect. It's considered better form to simply do

if (s === "test") {
  MyFunc();
} else {
  MyFunc2();
}

Apart from that it's perfectly solid syntax. I personally do agree that writing a terse ternary as an alternative to an if is bad and you're better off only using it for assignment.

Other short hand expression that have been (ab)used for terse-ness

someCondition && doMagic(magic);
someCondition || doMagic(magic);

Again these are considered bad form if there used only as expressions because using these just obscures logic away and make it harder to maintain code.

JSHint has an option expr for this. See ticket

Running:

/*jshint
  expr: true
*/

var s, MyFunc, MyFunc2;
s === "test" ? MyFunc() : MyFunc2();
0 === 1;

Will pass