Please note: as far as I'm aware this isn't a duplicate. There is some discussion about this warning in other languages but as we all know, == in JavaScript isn't like other languages.
The code reads:
let channelValue = filter == true ? 2 : 1;
SonarLint suggests "remove the unnecessary boolean literal, which tempts me to write:
let channelValue = filter ? 2 : 1;
but of course that will give a different result if filter has the value 87 or "Cheese on Toast". Is there a way to avoid the == true but retain the same semantics?
You should consider using === instead of == as the second one is not recommended and may behave unexpectedly. It also resolves sonarlint warning.
So you code should look like this:
let channelValue = filter === true ? 2 : 1;
Related
I've recently become informed of the ternary operator and it seems like an effective way of cleaning up my code. However, I seem to be confused with the possibilities of it.
I understand that you cannot use it for if-only conditions, but I'm a little confused about the logic of what I've done.
I wrote this:
if(current_slide < 1){
current_slide = 1;
ToggleEnabled(next_button);
}else if(current_slide > total_slides){
current_slide = 1;
ToggleEnabled(prev_button);
}
It works, whatever. I wanted to clean it up a little, so I made this:
current_side < 1 ? (ToggleEnabled(next_button), current_slide = 1) : current_slide > total_slides ? (ToggleEnabled(prev_button), current_slide = 1) : [No clue what to put here];
Is there a better way of doing this in a more tidy way, or should I just keep using the if-elseif- ?
In my opinion the ternary operator should not be chained. As #VLAZ expressed their concerns in their comment, the ternary can become excessively difficult to read if you chain it in multiples. In this situation I would stick with the traditional if-else.
Take a look at the following:
if (condition1) {
// do stuff #1
} else if (condition2) {
// do stuff #2
} else if (condition3) {
// do stuff #3
} else {
// do stuff #4
}
And compare the readability to the same in ternary (I tried to indent it clearly, but chained ternary formatting is a matter of opinion):
condition1
? // do stuff #1
: condition2
? // do stuff #2
: condition3
? // do stuff #3
: // do stuff #4
To my eye the first option is a lot more readable. There is not much to be gained even if you would understand chained ternary very well, as it is (slightly) less efficient than traditional if-else.
Also of note should be the fact that ternary always needs the both the ? and the :, which means there is always a "final else" that you must deal with.
IMO, the ternary operator is meant to choose between answers or values, based on a condition, e.g.:
const x = condition1 ? 1 : 2;
return condition2 ? func1(x) : func2(x);
If you don't use the resulting value from a ternary expression (as you do) then the usage becomes highly suspect to me, and I would most likely ask it to be changed in code review. Even more so if you move the assignment part to BEHIND the ? and : selectors as you did.
Not everything that is possible, is also good style, good practice or recommended.
I came across this expression in Angular documentation:
(name && name.trim()) || '<no name set>';
This is basically the same as
name ? name.trim() : '<no name set>';
I've tested this for the following inputs for name and both expression result in same:
function fn1(name){
return (name && name.trim()) || '<no name set>';
}
function fn2(name){
return name ? name.trim() : '<no name set>';
}
var inputs = [undefined, null, '','astring']
console.log(inputs.map(fn1));
console.log(inputs.map(fn2));
So the question using which one of the above is a better practice. I guess the ternary one is more readable. However, I appreciate your thoughts about this or anything that I might have missed.
UPDATE
I missed one test, which is an all white-space string. This results in different outputs.
function fn1(name){
return (name && name.trim()) || '<no name set>';
}
function fn2(name){
return name ? name.trim() : '<no name set>';
}
var inputs = [' ','\t']
console.log(inputs.map(fn1));
console.log(inputs.map(fn2));
As suggested by #T.J. Crowder this question can be framed in a less-opinion based form like:
Will (x && x.y) || z ever give a different result from x ? x.y : z?
But what I learned from this framing is more important. When you see a code like one in Angular doc, if you think of it in terms of something more general like above, you can see the difference better. Looking at the new question, it's easy that you see x.y might evaluate to false just like x. And because all values that evaluate to false are not the same because we have empty strings, undefined, etc., then the two expressions are not equal.
This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 6 years ago.
Is it possible to shorten this code?
var access_followup = user_access && user_access.followup && user_access.followup.access ? true : false;
Unfortunately JS does not have a null conditional operator. You could write helper function for it or use a slightly less effective method of creating dummy objects:
var access_followup = !!((user_access || {}).followup || {}).access;
which is shorter and prevents using the property names more than once, but doesn't improve readability. The !! is used to enforce a boolean value even when the values don't exist
Maybe I am answering the wrong thing, but why would you want to make it shorter? I'd vote to make it a bit longer, but easier to read for people who work with your code ( including you :) ).
You could make it more readable by splitting it up into multiple lines:
var access_followup = (
user_access &&
user_access.followup &&
user_access.followup.access === true // if access is a boolean value
);
Or, in case you really really want to have short code and you do not use a minifier already, you can try https://jscompress.com/ (which actually compresses any code you paste into it! but makes it WAY less readable).
If the first 2 checks are because you are protecting against exception thrown when user_access.followup is undefined, you can try this:
var accessFollowup;
try {
accessFollowup = !!user_access.followup.access;
} catch (e) {
accessFollowup = false;
}
You could also shorten by removing just the ternary by using !! to force last element into Boolean value:
var access_followup = !!user_access && !!user_access.followup && !!user_access.followup.access
very ugly code that works
var access_followup = (followup = (user_access || {}).followup) && followup.access;
So I'm using a shorthand JavaScript if/else statement (I read somewhere they're called Ternary statements?)
this.dragHandle.hasClass('handle-low') ? direction = "left" : direction = "right"
This works great, but what if later I want to use just a shorthand if, without the else portion. Like:
direction == "right" ? slideOffset += $(".range-slide").width()
Is this possible at all?
you can use && operator - second operand expression is executed only if first is true
direction == "right" && slideOffset += $(".range-slide").width()
in my opinion if(conditon) expression is more readable than condition && expression
Don't think of it like a control-block (ie: an if-else or a switch).
It's not really meant for running code inside of it.
You can. It just gets very ugly, very fast, which defeats the purpose.
What you really want to use it for is ASSIGNING VALUES.
Taking your initial example and turning it on its head a little, you get:
direction = (this.dragHandle.hasClass("handle-low")) ? "left" : "right";
See. Now what I've done is I've taken something that would have required an if/else or a switch, which would have been used to assign to that one value, and I've cleaned it up nice and pretty.
You can even do an else-if type of ternary:
y = (x === 2) ? 1 : (x === 3) ? 2 : (x === 4) ? 7 : 1000;
You can also use it to fire code, if you'd like, but it gets really difficult after a while, to know what's going where (see the previous example to see how even assignment can start looking weird at a glance)...
((this.dragHandle.hasClass("...")) ? fireMe(something) : noMe(somethingElse));
...this will typically work.
But it's not really any prettier or more-useful than an if or a branching, immediately-invoking function (and non-JS programmers, or untrained JS programmers are going to crap themselves trying to maintain your code).
The conditional operator is not a shorthand for the if statement. It's an operator, not a statement.
If you use it, you should use it as an operator, not as a statement.
Just use a zero value for the third operand:
slideOffset += direction == "right" ? $(".range-slide").width() : 0;
What you have will not work, but why not just use a one line if statement instead.
if(direction == "right") slideOffset += $(".range-slide").width();
This involves less typing than the method Ray suggested. Of course his answer is valid if you really want to stick to that format.
No, This is not possible, because ternary operator requires, three operands with it.
first-operand ? second-operand (if first evaluates to true) : third-operand (if false)
you can use && operator
direction == "right" && slideOffset += $(".range-slide").width()
This doesn't exactly answer your question, but ternaries allow you to write less than you've shown:
direction = this.dragHandle.hasClass('handle-low') ? "left" : "right";
And now that I think about it, yeah, you can do your question too:
slideOffset + direction == "right" ? = $(".range-slide").width() : = 0;
This is a theory. The next time I have an opportunity to += a ternary I will try this. Let me know how it works!
You can use this shorthand:
if (condition) expression
If in some cases you really want to use the if shorthand. Even though it may not be the best option, it is possible like this.
condition ? fireMe() : ""
Looks weird, does work. Might come in handy in a framework like Vue where you can write this in a template.
You can using Short-circuit Evaluation Shorthand. if you want the if condition just write the else condition.
let
a = 2,
b = a !== 2 || 'ok';
console.log(b);
I often see and use codes like:
var myvar = (1 < 2) ? 3 : 4 ; //if 1 < 2 then myvar = 3, else = 4
But I just recently saw a code that was executing code, just like some kind of replacement for the if(){}else{}:
Example:
(1 < 2) ? alert("example1") : alert("example2");
The first thoughts that came to me were, "wow, this is like 6-7 characters shorter", "endless of possibilities" or "this made my day".
My question:
Is this thing error-free and safe to use? (like, with a lot of code inside, and nested stuff)
For now, I will just keep using it in the normal way, I have the fear that if I start using it to execute pieces of code might not work.
Is this thing error-free and safe to use? (like, with a lot of code
inside, and nested stuff)
Yes. However, the more code that's within it, the less readable it becomes.
I prefer to use it (the conditional operator) for short, concise statements. Anything more complex deserves an if/else for the sake of readability and maintainability.
There are some exceptions. You can't do this with:
break
continue
Any block like if, for, while, do, or try
for example. What's more, it can mess with your order of operations:
x < 3 ? l = true : r = true; // Syntax error, = has lower precedence than ?:
But that's not the reason not to do it, it's because it's ugly. Which one is clearer to you, this:
if(i > 5) {
alert('One');
} else {
alert('Two');
}
or
i > 5 ? alert('One') : alert('Two');
? It's not quite right, is it? And saving characters is never a reason to do anything, really; otherwise there would be no comments or whitespace. A good minifier like Google Closure Compiler will automatically convert these for you when possible, and there are plenty of other places to save. In the end, it's just whatever you find most convenient and readable.
Also, if you do end up needing break, continue, etc. then it's going to be rather inconsistent and unattractive code.
You're referring to the ternary operator. It's usually used for setting variables with simple strings like this:
var phone = old ? "blackberry" : "iPhone"
That much simpler than using an if:
var phone = "iphone"
if (old) {
phone = "blackberry"
}
It's good in this context, in the example you described and as soon as it starts getting confusing or I'd definitely not recommend it!
Your example might be made better like this:
var msg = 1 < 2 ? "alert1" : "alert2";
alert(msg);
You could also write:
alert( 1<2? "example1" : "example2" );
The ternary opertator is designed for simple cases, sometimes developers get carried away and use it to replace multiple if..else statements, e.g.
var someVal = foo < bar? 'yes' : bar > fum? : fum : fi != fee? fi : fee;
which is not a good idea IMHO.