Question

Sometimes I use ternary statements to simplify & reduce the length of my code.

Ternary statements are traditionally used to assign a value to a variable, but in JS I can also write ternary statements with no assignment to execute differing outcomes based on the boolean response to the question - example:

anyVariable > someValue ? 
    funcOne(anyVariable): 
    funcTwo(anyVariable);

This code throws no errors, but jsLint complains that it saw an expression where it expected an assignment or function call.

Are there any pitfalls or potential issues I should be aware of when using ternary statements (in Javascript) in this fashion?

Was it helpful?

Solution

There should not be any pitfalls in this fashion. Consider the following statement -

b = a = 10;

we can omit the "b=" portion of the statement without any issues. And its the same case for the ternary statements.

Generally you should avoid this type of use because an error in previous lines may cause problem with the later code. But if you use if-else then you can avoid such problems.

// user made a typo on the first line. but this code has correct syntax 
b = 10 +
a > 10 ? fun(20) : fun(0);

// same scenario using if-else will generate a compilation error which is preferred.
b = 10 +
if (a>10) {
    fun(20);
}
else {
    fun(0);
}

OTHER TIPS

JS(L|H)int is going to complain about that because it's just a expression and not a statement. In cases like this, it's "better" (argumentative) to use an if:

if(anyVariable > someValue){
    funcOne(anyVariable);
} else {
    funcTwo(anyVariable);
}

edit If terseness is a goal you can always omit the curly braces:

if(anyVariable > someValue) funcOne(anyVariable)
else funcTwo(anyVariable);

/edit

The bonus here is that your code is more readable (since it's all assignments or function calls), and if you need to extend or do more than one operation in each clause, you're set up for it.

Where the ternary operator is used well, however, is in assignments:

var thisVariable = someValue > thatValue ? someValue : thatValue;

That will pass the linter, and the statement, while terse, is still pretty readable, however, when testing against "falsey" values, I do prefer:

var thisVariable = someValue || thatValue;

If someValue is "falsey", it will set thisVariable to thatValue.

I'd avoid it, if you use it incorrectly then it'll cause errors (I've seen invalid left hand assignment amongst others). If you're using a good minifier (such as Uglify), it'll do all this for you when running your build process - which keeps your development code readable and easy.

I'd stick with using it for assignment only.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top