I have a ternary operator dir === 'next' ? ++$currentSlide : --$currentSlide;
in my JS used to increment of decrement an integer. when I run my script in grunt JSHint hightlights this line as Expected an assignment or function call and instead saw an expression.
Can anyone advise where I'm going wrong with this? Should I set my condition up differently etc?
I have a ternary operator dir === 'next' ? ++$currentSlide : --$currentSlide;
in my JS used to increment of decrement an integer. when I run my script in grunt JSHint hightlights this line as Expected an assignment or function call and instead saw an expression.
Can anyone advise where I'm going wrong with this? Should I set my condition up differently etc?
Share Improve this question asked Aug 5, 2013 at 13:55 stylerstyler 16.5k25 gold badges85 silver badges139 bronze badges5 Answers
Reset to default 21You are misusing the conditional operator as an if
statement, that's why you are getting that note. The real work in the code is done as a side effect of the expression, and the result of the expression is ignored.
As a real if
statement, it would be:
if (dir === 'next') {
++$currentSlide;
} else {
--$currentSlide;
}
You can use the conditional operator if you use it as an actual expression:
$currentSlide += dir === 'next' ? 1 : -1;
In general, for disabling the 'Expected an assignment or function call and instead saw an expression.' warning, you can do /* jshint expr: true */
Does it pass if you write it like this?
$currentSlide = (dir === 'next' ? $currentSlide + 1 : $currentSlide - 1);
Linters and hinters usually don't like in/decrements because they're sensitive to bugs.
Try this syntax:
$currentSlide = (dir === 'next' ? $currentSlide+1 : $currentSlide-1);
make ternary operator in to if else condition
Before:
(pbook.id === book.id ? book.shelf = pbook.shelf : "none");
After:
if(pbook.id === book.id){
return book.shelf = pbook.shelf
} else {
return "none"
};