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?
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
Example: JavaScript Ternary OperatorEnter your marks: 78 You pass the exam. Suppose the user enters 78. Then the condition marks >= 40 is checked which evaluates to true . So the first expression pass is assigned to the result variable.
A ternary operator is a three-operand operator that is supported in most programming languages, including JavaScript, Java, C++, C#, and many others.
The ternary operator shortens this if/else statement into a single statement: result = (condition) ? 'something' : 'somethingelse'; If condition is true, the ternary operator returns the value of the first expression; otherwise, it returns the value of the second expression.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With