More compact "if...else if" when executing same code - javascript

I have a JavaScript calls structured this way:
if (($(this).scrollTop() == 0) && !controlsVisibility) {
triggerControls();
}
else if (currentScroll > (previousScroll + 100) && controlsVisibility) {
triggerControls();
};
While triggerControls() does just-in-case typecheck for undefined, and uses controlsVisibility as default arg determine what exactly it is supposed to do. I think:
Did I made a mistake of not passing controlsVisibility as a function arg inside if clause. If value of that variable changes between I call triggerControls() and function's execution (microsecond?) — should I:
account for the possible change by using the global state (as it is now)
or
interfere the change by passing stable args in advance?
I understand that this might be determined on case-by-case basis, but I would really appreciate some tips.
If the current implementation (1) is OK
I could've written both scenario checks in one if just by using || as I am executing the same function. Except for being messy and making the code largely unreadable why shouldn't I do just that?

If value of that variable changes between I call triggerControls() and function's execution (microsecond?)
No. While your script is executing, nothing else will change that variable - JavaScript is single-threaded. Unless triggerControls does something asynchronous and expects the value to be the same in a future turn of the event loop, everything is fine.
I could've written both scenario checks in one if just by using || as I am executing the same function. Except for being messy and making the code largely unreadable why shouldn't I do just that?
I don't see a reason not to do that. It's not messy to avoid repetition (but dry), and I wouln't consider it unreadable. You even might use the ternary operator to shorten (and optimise) it:
if (controlsVisibility
? currentScroll > (previousScroll + 100)
: $(this).scrollTop() == 0
) {
triggerControls();
}

I disagree with the statement that rolling the two conditions with an || operator is unreadable. With the right formatting it is very readable:
if (
(($(this).scrollTop() == 0) && !controlsVisibility) ||
(currentScroll > (previousScroll + 100) && controlsVisibility)
) {
triggerControls();
};
That's clearly two conditions switched by controlsVisibility. I personally would prefer controlsVisibility to be checked first to make the fact that it's a switch clearer:
if (
(controlsVisibility && currentScroll > (previousScroll + 100)) ||
(!controlsVisibility && ($(this).scrollTop() == 0))
) {
triggerControls();
};
However, you also asked if there is a more compact way to write this and there is:
if (controlsVisibility ?
currentScroll > (previousScroll + 100) :
$(this).scrollTop() == 0
) {
triggerControls();
};
I'd argue that the code above is obvious and readable but not everybody likes the ternary operator.

Related

Is it possible to use the ternary operator for an if, if else, without a final else?

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.

&& / || operator strangeness in JavaScript

So, I was working on a project of mine, when I came across a problem like this:
var one = 1;
var two = 2;
var three = 7;
if (one === 1 || two === 2 && three === 3) {
console.log("ok"); // prints out ok
}
I'm pretty confused with this since I don't think it should print out "ok". I thought that since the condition after the && operator was false, it shouldn't run, but I'm evidently wrong. Can anyone clarify why it's working?
In Javascript, operators are not just evaluated left-to-right, certain operators have more precedence than others. Those with higher precedence (in this case, the && operator of precedence 13) will be evaluated before others (||, precedence 14).
For your particular case, you need to group your conditionals in order to achieve the functionality you want:
if ((one === 1 || two === 2) && three === 3) {
console.log("ok"); // prints out ok
}
JSFiddle

JavaScript shorthand if statement, without the else portion

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);

Is it safe to run code inside the conditional operator?

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.

Using function in Javascript

Example:
function pcs()
{
var t1 = document.getElementById("tot1").value
var pb = document.getElementById("pcbox").value
var pc = ""
if (t1==! && pb==!)
{
document.getElementId("rbox").innerHTML = ""
}
}
My question is if t1 and pb are null the function pcs() is not called... Why?
The line
if(t1==! && pb==!)
is not legal syntax. If this is exactly how you have written the code it will not parse and thus the function will not be defined (plus you'll be getting Javascript errors).
Perhaps you meant
if(t1 != null && pb != null)
Additionally, while semicolons at the end of lines can be inferred by the interpreter, they are meant to be there (as opposed to being actually optional) and adding them is good practice.
EDIT and while I didn't understand your final question 100%, remember that the code you've written (assuming the syntax were correct) merely defines a function. You will need to have some other code call this function at an appropriate point in order to have it executed, e.g. for some element onblur = pcs();
The line if(t1==! && pb==!) is nonsense - did you mean if (!t1 && !pb)?
if(t1==! && pb==!) --> this is absolutly wrong.... What are you trying to check?
Maybe if(t1!="" && pb!="")?

Categories

Resources