16

I am using JSLint to ensure my JavaScript is "strict" and I'm getting the following error:

Expected an assignment or function call and instead saw an expression

On the following code:

(my_var > 0 ) ? $("#abc").html(my_array.join('')) : $("#abc").html('<h2>Hello ' + persons_name);

Any ideas why I'm getting such an error? Also, I'm using jQuery as seen in the above code, in case that makes a difference.

Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
HeatherK
  • 2,293
  • 4
  • 20
  • 12

4 Answers4

14

My guess would be that JSLint is unhappy since you're using the ternary operator, and you're not doing anything with the value. Refactoring this into the equivalent:

if (my_var > 0 ) {
  $("#abc").html(my_array.join(''));
} else {
  $("#abc").html('<h2>Hello ' + persons_name);
}

would eliminate the error. If for some reason you're really attached to using the ternary operator, the "right" way to use it would be:

$("#abc").html((my_var > 0) ? my_array.join('') : '<h2>Hello ' + persons_name);
Mark Bessey
  • 19,598
  • 4
  • 47
  • 69
8

I believe this is because the ternary operator evaluates the expression and returns a value that is expected to be assigned. For example:

var test = (my_var > 0) ? true : false;

However, you are using it like a regular if/then/else statement. While the ternary operator does perform if/then/else, it is traditionally used in assignents.

EDIT: As an addendum: would this statement make sense to you?

var foo = 1;
(my_var > 0) ? true : false;
console.log('hello world');
Matt
  • 41,216
  • 30
  • 109
  • 147
2

you are using an expression (an expression using the ternary operator to be precise) in a single line: your line is comprised uniquely of an expression.

this is considered poor programming practice in many language, and could be rewritten using an if statement to render this line more clear.

Adrien Plisson
  • 22,486
  • 6
  • 42
  • 73
0

Just asked the same Q without finding this one for some reason...

The ternary returns a value that isn't being used so you're abusing the ternary structure by not using the value (even though the function calls are being made as intended).

Campbeln
  • 2,880
  • 3
  • 33
  • 33