Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator displays error in JSHint - Expected an assignment or function call and instead saw an expression

Tags:

javascript

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?

like image 885
styler Avatar asked Aug 05 '13 13:08

styler


People also ask

How do you ignore expected an assignment or function call and instead saw an expression?

The React. js error "Expected an assignment or function call and instead saw an expression" occurs when we forget to return a value from a function. To solve the error, make sure to explicitly use a return statement or implicitly return using an arrow function.

What is the format of conditional operator?

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.

How do you use the conditional operator in Ruby?

Conditionals are formed using a combination of if statements and comparison and logical operators (<, >, <=, >=, ==, != , &&, ||) . They are basic logical structures that are defined with the reserved words if , else , elsif , and end .


2 Answers

You 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;
like image 175
Guffa Avatar answered Oct 16 '22 01:10

Guffa


In general, for disabling the 'Expected an assignment or function call and instead saw an expression.' warning, you can do /* jshint expr: true */

like image 8
learner_19 Avatar answered Oct 15 '22 23:10

learner_19