JavaScript - If statement in if statement condition - javascript

I want to check for an element's existence in the if statement condition, and if so then use the element as part of the comparison. Something like this:
if( if($(".element").length > 0) { $.contains( $(".element")[0], $("[ele]")[0] )} ) {...
I know I could just nest if statements, like:
if($(".element").length > 0) {
if($.contains( $(".element")[0], $("[ele]")[0] )) {....
But is there a shorter way to do this? Can if statements be used in another if statement's condition like this in some way?

You can use the && operator to chain both of your conditions:
if($(".element").length > 0 && $.contains( $(".element")[0], $("[ele]")[0] )) {
If the the first condition fails (code prior to &&), it will short out and not execute the second condition.

You can use the && (and) operator for that. If the thing on the left side of the && is false, then it doesn't evaluate the right side of &&, so you don't have to worry about any errors from the element not existing. (This is called short-circuit evaluation, and || (or) does a similar thing, except || doesn't evaluate the right side if the left side it true.) So
if($(".element").length > 0 && $.contains( $(".element")[0], $("[ele]")[0] )) ...
It's not necessary here, but if you want an if-else inside an expression, you can use the ?: (ternary conditional) operator. condition ? a : b is like if(condition) a else b, except it's actually an expression, so for instance, x = (condition ? a : b) is the same as if(condition) x = a; else x = b;.

Related

logical OR and precedence

I've just been watching a tutorial which talked about the following if statement:
var a = 0;
if(a || a === 0){...};
It states that operator precedence means that a === 0 is evaluated first, as it has a higher precedence than ||.
I've no real issue with that, but the tutorial goes on to say that 'a' is then evaluated - but surely it's short-circuited?
I know it should be pretty simple, but I'm new to JS. Is this a mistake or am I misunderstanding what's being said?
You can test this easily enough with a getter. If a is true, the getter is called once, meaning that obj.a === 0 is never evaluted due to short-circuiting:
let obj = {
get a() {
console.log("getting a")
return true
}
}
if(obj.a || obj.a === 0){
console.log("true")
};
If a is falsey as is the case when a id 0 , both side are evaluated:
let obj = {
get a() {
console.log("getting a")
return 0
}
}
if(obj.a || obj.a === 0){
console.log("true")
};
No, the equivalence doesn't happen first:
var a = 0;
if(a || a === 0){...}
The a in this case is falsey and so the || continues onto the next statement, equivalent to:
if(a === 0){...}
At this point, the equivalence takes place and is clearly true, no short circuiting takes place because the expression is evaluated left to right.
The reason for this is that either side of the OR is a different expression and the expressions are evaluated from left to right.
expr1 || expr2
Once expr1 has been evaluated, if it is truthy only then does short-circuiting take place and the expression as a whole be truthy. If this isn't the case expr2 will be evaluated and if that is truthy then the expression as a whole will be truthy, otherwise it will be falsey.

What kind of javascript conditional statements are these?

In some code I inherited at work, I'm trying to figure out how these conditions work here, but I'm unsure of how it's structured and what type of conditional statements these are (this originated the jQuery jBox plugin)
this._fireEvent = function( event, pass ) {
// This condition here
this.options[ event ] && ( this.options[ event ].bind( this ) )( pass );
};
And this second condition:
this.options.pointTo == 'target' && (!this.options.outside || this.options.outside == 'xy') && (this.options.pointer = false);
The first one I can tell, in a traditional if statement, would be...
if ( this.options[ event ] ) {
this.options[event].bind( this )( pass );
}
Is there a name or methodology for these types of conditional statements? And how would you read that second one in terms of what it's doing?
Would really appreciate any help or insight that someone could provide!
this.options[ event ] && ( this.options[ event ].bind( this ) )( pass );
if equivilent to
if (this.options[ event ] )
( this.options[ event ].bind( this ) )( pass );
or
this.options[ event ] ? ( this.options[ event ].bind( this ) )( pass ) : null
this
this.options.pointTo == 'target' && (!this.options.outside || this.options.outside == 'xy') && (this.options.pointer = false);
is almost the same as
this.options.pointTo == 'target' ? (!this.options.outside : this.options.outside == 'xy') && (this.options.pointer = false);
or the equivalent if statement of course
so to sum up:
&& will execute the right side if and only if the left side is true
|| will execute the right side if and only if the left side if false
They are just compound statements that include the short-circuited logical AND (&&) and the short-circuited logical OR (||) operators to test for multiple things at once.
Short-circuited AND means that if any condition fails (processing
from left to right), the entire expression fails and do not continue
to evaluate the expression.
Short-circuited OR means that if any condition succeeds
(processing from left to right), the entire expression succeeds and
do not continue to evaluate the expression.
Additionally, the grouping operator () is used to group conditions together, effectively creating conditions that must be evaluated independently of the rest of the expression.
Its called short circuit statement evaluation. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
And you read it based on the order of precedence: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
So in your case it will be read as:
'target' && (!this.options.outside || this.options.outside == 'xy') && (this.options.pointer = false);
First_truthy_value && (Second block evaluation) && (Third block evaluation which finally gets returned as a 'value')
Your third block however is an assignment statement this.options.pointer = false which will always return false

How to convert ternary to if/else condition

This is what my ternary looks like now, but I'd like to see how this looks as an if/else block
function showResultBox(v){
v ? searchResultBox() : hideBox()
}
A ternary is way of formatting a conditional that is limited to just an if | else. That is, there is no room for any else if blocks.
Here is what's happening in v ? searchResultBox() : hideBox():
1 2 3
Evaluate v for truthiness.
If v is truthy, call the searchResultBox function.
Otherwise, call the hideBox function
As a non-ternary conditional, your example would look like this:
if (v) {
searchResultBox();
} else {
hideBox();
}
You can experiment with the following examples (fiddle here) to get a better feel for what's going on:
true ? console.log("stark") : console.log("baratheon")
false ? console.log("stark") : console.log("baratheon")

What do you call the double pipe in javascript, as used in this context?

People often write this in order to specify default values:
var thing = this || that;
which is, AFAIK, the same thing as this:
var thing = !!this ? this : that;
What do you call the technique used to specify defaults in the first code block?
NOTE: I am not asking what a logical OR is called. I am asking what the alternative to ternary notation (as written in the first code block) is called.
I'd call:
var a = A || B;
conditional assignment, since it is effectively:
if (!!A) {
a = A;
} else {
a = B;
}
and it is a replacement for the conditional operator : ?
var a = A? A : B;
It might also be called "logical assignment" since it involves a logical OR expression, but it doesn't seem to fit with what it's doing.
As mentioned elsewhere it is a logical OR.
The evaluation in question is a short-circuit evaluation.
It might help to look at it like this:
if ((foo = bar)) {
} else {
foo = baz;
}
The if statement evaluates to the value of bar. If bar is false, null etc the evaluation would be false.
Edit: Note:
It is perfectly valid to evaluate an assignment. If we say:
if ((a = b)) { ...
note that it is not:
if (a === b) { ...
the evaluation is done on the result of the assignment. Here it would evaluate to true if (b).
One should however always wrap them in parenthesis. This makes it clear that we are evaluating the assignment and not comparing the variables.
If one do not like it that is fair enough, (I'm rather used to it from C), but in this case it is merely for the sake of the answer to the question.
In the same way we have:
if ((foo = foo)) {
} else {
foo = baz;
}
var x = false;
console.log((x = x)); // False
As such we can say:
(x = x) || (x = y)
And to make it short:
x = (x || y);
or shorter:
x = x || y;
The double pipe is called the 'or' operator.
The double pipe is the Logical OR operator in JavaScript.
If the technique had a name I guess it would be "(ab)using the short-circuiting of the logical OR operator"

testing multiple variables in a conditional ? Dom Javascript

The code below represents the idea I am trying to achieve but when I test it doesn't work, what would be the appropriate way to test if q1 and q2 is equal to true?
function processForm() {
if(q1_valid = true && q2_valid = true){
alert("yes");
} else {
alert("no");
}
}
When you use simple = in javascript (and most C-like languages), what happens is that you assign the variable, then return the result of said assignment.
For instance, take the code a = b = true. This can be split up into a = (b = true). Now, if we only look at the part inside the parenthesis, you'll see that what it does is first set b to true, then return b. Then, outside the parenthesis it sets a to whatever b was (which ofcause is true), and returns the value of a. The value of a has nowhere to go, so it's simply dropped.
Now, if we go back to your if-test, what you end up with is basically this:
Set q1_valid to true.
return true (the value of q1_valid) to the && operator.
true is valid for && so it looks at right hand side.
Set q2_valid to true.
return true to the &&.
&& now has true on both sides. Returns true.
Test always passes. q1_valid and q2_valid will always be true after test is run.
The simple solution is to replace = with either == (equals) or === (type and value equals). Your if-check should look like one of the following:
1.
if(q1_valid == true && q2_valid == true)
2.
if(q1_valid === true && q2_valid === true)
Also, since working with booleans (values that are either true or false), the check for equality to true can be omitted altogheter. Another way to do this is simply like this:
if(q1_valid && q2_valid)
Two issues here:
You need to use two equals signs for comparison ==
The variables don't exist in the function, you would need to pass them as parameters when calling the function
function processForm(q1_valid, q2_valid) {
if(q1_valid == true && q2_valid == true){
alert("yes");
} else {
alert("no");
}
}

Categories