"Do nothings" as statment in Javascript Condition - javascript

I want a ternary operator in JavaScript to return nothing if the statment is false
I have tried this:
1 == 1 ? alert('YES') : '';
But I want to know if this is the right way to make a statments "DO NOTHING" depending on the condition.

No, use if.
if (1 == 1) {
alert('YES');
}
Don't abuse the conditional operator as a replacement for if/else - it's confusing to read. I'd also recommend always using === instead of ==.

If you really want to do it, && will be one way.
1 == 1 && alert('ALERTED');
1 == 2 && alert('NOT ALERTED');
It is single statement.
A condition after an AND operator is only run if the first is true. So it is like an if statement.

did you try a single line if statement without brackets?
if(1 == 1) alert('Yes');

Related

Ternary operator multiple statements [duplicate]

This question already has answers here:
Javascript - Ternary Operator with Multiple Statements
(5 answers)
Closed 3 years ago.
I want to do multiple things if the condition is true or false. I tried to wrap the statements in a { } but it doesn't work. So my code:
theId == this.state.correctId ?
console.log("Correct Id!") :
console.log("TRY AGAIN")
I tried:
theId == this.state.correctId ?
{console.log("Correct Id!"); //semicolon does not make any difference
this.setState({counter: this.state.counter+1})
} :
console.log("TRY AGAIN")
This doesn't work. How do I add multiple statements if the condition is true or false?
Thanks.
The conditional operator should only be used when you need to come up with an expression that is (conditionally) one thing or another, eg
const something = cond ? expr1 : expr2;
Because that's not the case here (and you want to log or call setState), the conditional operator is not appropriate; use if/else instead:
if (theId == this.state.correctId) {
console.log("Correct Id!")
this.setState({counter: this.state.counter+1});
} else {
console.log("TRY AGAIN");
}
You could technically slightly tweak your original code by using the comma operator to combine expressions:
theId == this.state.correctId
? (
console.log("Correct Id!"),
this.setState({counter: this.state.counter+1})
)
: console.log("TRY AGAIN");
But that's very hard-to-read, and is not what a reader of your code would expect to see from the conditional operator, so should probably be avoided.
Using the conditional operator when the resulting expression is not going to be used should probably be reserved only for code-golfing and minifying, but not in professional source code, where readability is extremely important.
You can use the comma operator, like this:
const ret = true ?
(console.log("1"),
console.log("2"),
"3")
: console.log("nope");
console.log(ret);

Shortening my IF statement containing both: & and ||

Here's my code:
if(whats.above(x,y)=="g" && whats.onLeft(x,y)=="g") {
$(this).css("border-top-color","green").css("border-left-color","green");
}
whats.above and whats.onLeft can return some letters. In this case, my statement checks if it's going to return g in both cases.
However, I have more letters now, and I want this statement to be true for more of them. Here, there's only one letter, g, but I want some others, for example n. I know I cannot do something like this:
if(whats.above(x,y)==("g"||"n"))
What can I do to minimalize my code in this case?
You could use String#indexOf with a string with the letters.
if ('gn'.indexOf(whats.above(x,y)) !== -1) {
Well, The problem is in your statement is it should be
if(whats.above(x,y)=="g"|| whats.above(x,y) == "n"){ }
For a better solution, I would go with
if (["g","n"].indexOf(whats.above(x,y)) > -1){ }

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

javascript if condition && condition doesn't work

the AND && operator doesn't work, but when i replace it with an OR || operation it is workin, why? I just used OR || operator for testing, what i need is an && operator.
Please help. thanks
function validate() {
if ((document.form.option.value == 1) && (document.form.des.value == '')) {
alert("Please complete the form!");
return false
} else return true;
}
i also tried nested if but it doesn't work too
if(document.form.option.value==1)
{
if(document.form.des.value=='')
{
alert ("Please complete the form!");
return false
}
}
It sounds like || is what you are looking for here. The && operator is only true if both the left and right side of the && are true. In this case you appear to want to display the message if the value is 1 or empty. This is exactly what the || operator is for. It is true if either the left or right is true
If Or operator is working, means there are some javascript errors in your second part of condition. check document.form.des.value=='' (maybe just open your javascript console in Chrome/Firefox/IE8+)
its because one of the conditions specified above returns false and loop breaks. Is you use OR ,only one must be validated and returns true.. check your code for both the conditions.

Categories

Resources