What kind of javascript conditional statements are these? - javascript

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

Related

JavaScript - If statement in if statement condition

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

Difference between exclamation equals sign and exlamation 2x equals sign when checking with null

What is the difference between next if statements in javascript when checking with null?
var a = "";
if( a != null ) // one equality sign
....
if( a !== null ) // two equality sign
....
When comparing to null I can't find any difference.
According to http://www.w3schools.com/js/js_comparisons.asp
!= - not equal
!== - not equal value or not equal type
In JavaScript, null has type: object (try yourself executing the following sentence typeof null).
That is, !== will check that a is also object before checking if the reference equals.
Actually you know that === and !== are meant to check that both left and right side of the equality have the same type without implicit conversions involved. For example:
"0" == 0 // true
"0" === 0 // false
Same reasoning works on null checking.
!= checks
negative equality
while !== checks for
negative identity
For example,
var a = "";
a != false; //returns false since "" is equal false
a !== false; //returns true since "" is not same as false
but if you are comparing it with null, then value will be true in both ocassion since "" is neither equal nor identical to null
There is no difference between them when comparing to null.
When we use strict equality (!==) it is obvious because they have different types, but when we use loose equality (!=) it is an important thing to remember about JavaScript language design.
Because of language design there are also some common questions:
How do you check for an empty string in JavaScript?
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
var a = "";
(1) if( a != null ) // one equality sign
Above condition(1) checks value only and not data-type, this will return true.
....
(2) if( a !== null ) // two equality sign
This checks value and data-type both, this will true as well.
To understand it more precisely,
var a = "1";
if( a == 1) {
alert("works and doesn't check data type string");
}
if( a === 1) {
alert('doesn't works because "1" is string');
}
if( a === "1") {
alert('works because "1" is string');
}
There is a difference if variable has value undefined:
var a = undefined;
if( a != null ) // doesn't pass
console.log("ok");
if( a !== null ) // passes
console.log("ok");
Got idea from reading this great post Why ==null, Not ===null. Also != is faster.

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

Checking whether a variable is null or NOT

var DEST_VALUE = 1
var APPDAYS_AFTER = 2
}
How can i check whether the variable holds some value or not. When i do this, it does not work...
Of course it doesn't do anything, because in your example DEST_VALUE resolves to true like APPDAYS_AFTER. Value that resolve to false when converted to a boolean in javascript are:
false
null
undefined
The empty string ''
The number 0
The number NaN (yep, 'Not a Number' is a number, it is a special number)
if you write
if(!DEST_VALUE){
txtSiteId.value = fileContents.Settings.SiteID;
}
you write "if DEST_VALUE is not true do something" (in your case it does nothing). If you want to check if a variables hold a value:
if(DEST_VALUE !== undefined){
//do something
}
I use such function to check if variable is empty or not:
function empty( mixed_var ) {
return ( typeof(mixed_var) === 'undefined' || mixed_var === "" || mixed_var === 0 || mixed_var === "0" || mixed_var === null || mixed_var === false );
}
I assume you mean "holds some value" like in "the variable has been created so it exists", right? Otherwise, your approach works perfectly fine.
If you want to check whether a variable exists in javascript, you have to check its parent object for the property - otherwise the script will fail. Each object in javascript belongs to a parent object, even if it seems to be global (then, it belongs to the window object). So, try something like:
if (window.DEST_VALUE)
// do something

Javascript or operator not working

var strExt = GetAttributeFromItemTable(itemTable, "Ext", "FileType");
I did a alert for strExt and it resolves.
if (strExt!='wav')
{
// this works
}
if (strExt!='wav' || strExt!='mp3')
{
// this does not work.
}
Your logic is flawed:
if your variable strExt was equal to 'wav' it would not be equal to 'mp3', and versa-visa.
Please explain your desired results more clearly.
I think what you're trying to say is something like (neither 'wav' nor 'mp3'):
if ( !( strExt == 'wav' || strExt == 'mp3' ) )
which is logically equivalent to (not 'wav' and not 'mp3'):
if ( strExt != 'wav' && strExt != 'mp3' ) )
|| says: if any condition is true, It'll return true, without looking at the ones after it.
So true || false is true, false || true is true.
In your case, you say "if strExt is not equal to wav and is not equal to mp3, then execute the code". In case that one of them is true, it executes.
I'm thinking that you're looking for the && symbol. The logical and says "I'll return true only if every condition is true" - when it hits a false, it returns false.
What I think your code should look like:
if (strExt!='wav' && strExt!='mp3')
I would expect the result of the second expression to be True regardless of the value of the string strExt (any extension is either not equal to "wav" or not equal to "mp3"). What do you expect?
Are you certain you don't mean a Boolean AND instead of an OR ("extension is neither 'wav' nor 'mp3'")?
just add the another parenthesis, like so:
if ((strExt!='wav') || (strExt!='mp3'))
{
// this does not work.
}
The logic behind this makes no sense wouldn't you want to do:
if ((strExt !== "wav") && strExt !== "mp3") {
}
AND instead of OR makes more sense in this situation.
If you want to get into second if, when strExt is not equal to both 'wav' and 'mp3' you need to use an && operator.
if (strExt!='wav' || strExt!='mp3')
when strExt='wav' => strExt!='wav' = false; strExt!='mp3' = true => false or true = true and gets into if statement and is the case is similar when strExt='mp3' .

Categories