The ternary operator displays an error in JSHint - it was expecting a destination or function call and instead saw an expression

Do I have a ternary operator dir === 'next' ? ++$currentSlide : --$currentSlide; dir === 'next' ? ++$currentSlide : --$currentSlide; in my JS used to increase the decrement of an integer. when I run my script in grunt JSHint, this line lights up as Expected an assignment or function call and instead saw an expression.

Can someone tell me where I am going wrong? Should I configure my state differently, etc.?

+8
javascript
source share
5 answers

You are not using the conditional operator correctly as the if , so you get this note. The real work in the code is performed as a side effect of the expression, and the result of the expression is ignored.

As a real if , it will 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; 
+16
source share

In general, to disable the function "Expected Assignment or Call of a Function" instead of an expression instead. warning, you can do / * jshint expr: true * /

+7
source share

Does it go away if you write it like this?

 $currentSlide = (dir === 'next' ? $currentSlide + 1 : $currentSlide - 1); 

Linter and hinters usually do not like in / decrements, because they are error-sensitive.

+3
source share

Try this syntax:

 $currentSlide = (dir === 'next' ? $currentSlide+1 : $currentSlide-1); 
0
source share

make ternary operator for 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" }; 
0
source share

All Articles