An explanation of && shorthand in JavaScript - javascript

Using a watermark plugin for jQuery, I'm attempting to jslint and minimize the functions but I've come across syntax I have never seen before wherein there are expressions where there really ought to be an assignment or function call:
(function($) {
$.fn.watermark = function(css, text) {
return this.each(function() {
var i = $(this), w;
i.focus(function() {
w && !(w=0) && i.removeClass(css).data('w',0).val('');
})
.blur(function() {
!i.val() && (w=1) && i.addClass(css).data('w',1).val(text);
})
.closest('form').submit(function() {
w && i.val('');
});
i.blur();
});
};
$.fn.removeWatermark = function() {
return this.each(function() {
$(this).data('w') && $(this).val('');
});
};
})(jQuery);
I'm specifically interested in the following lines:
w && !(w=0) && i.removeClass(css).data('w',0).val('');
and
!i.val() && (w=1) && i.addClass(css).data('w',1).val(text);
Can someone explain this shorthand and rewrite these functions in such a way that I could compare them to better to understand the shorthand myself?
Thank you.

Let's break each of the statements you're asking about down to their components:
w && !(w=0) && i.removeClass(css).data('w',0).val('');
w - Is w "true"? (checking for != 0 in this case)
!(w=0) - Set w to 0, take the opposite of the result so the && chain continues
i.removeClass(css).data('w',0).val('') - Remove the class, set the data to 0 clear the value.
!i.val() && (w=1) && i.addClass(css).data('w',1).val(text);
!i.val() - Is the input empty?
(w=1) - Set w to 1
i.addClass(css).data('w',1).val(text); - Add the class, set the data to 1 and set the text to whatever the watermark text is.
Both of these are just statements to really cut down on code, certainly at the expense of readability. If you're looking at a de-minified version this is very common, if you're not and this is the original, chase the author with a salad fork, the original should be more more readable than this IMO, though it's just fine for a minified version.

&& can be used as a "guard." Basically it means stop evaluating the expression if one of the operands returns a "falsy" value.
Negating an expression will convert it to a boolean value. Specifically one that is a negation of the expression depending on whether it's 'truthy' or 'falsy'.
w && !(w=0) && i.removeClass(css).data('w',0).val('');
Basically says:
w is "truthy" (defined, true, a string, etc.)
AND set w to zero + convert the expression to true (because (w=0) would evaluate to 0, which is falsy)
AND evaluate i.removeClass(css).data('w',0).val('')

These can be rewritten as:
// w && !(w=0) && i.removeClass(css).data('w',0).val('');
if (w) {
if (!(w=0)) {
i.removeClass(css).data('w',0).val('');
}
}
//!i.val() && (w=1) && i.addClass(css).data('w',1).val(text);
if (!i.val()) {
if (w=1) {
i.addClass(css).data('w',1).val(text);
}
}
Using && like this is just a shorthand for using nested ifs. It's advantages being:
Uses marginally fewer characters than the exploded nested ifs, decreasing the payload that's delivered to the browser.
Can be faster to read for the trained eye.
Though, I must say that the above examples are an abuse of this shorthand because the conditionals used are fairly complex. I only resort to this shorthand when I need to check a chain of simple things like in the following example:
function log(s) {
window.console && console.log && console.log(s);
}

&& is And. It's for comparison / compound conditional statements. It requires that both conditions in an if statement be true. I do not think there is another way to rewrite it - that is the syntax for And.

With respect to:
w && !(w=0) && i.removeClass(css).data('w',0).val('');
the code:
!(w=0) && i.removeClass(css).data('w',0).val('');
will only execute if
w
is truthy.

Using
w && !(w=0) && i.removeClass(css).data('w',0).val('');
for this explanation, it allows you to string multiple commands together while ensuring that each is true.
This could also be represented by:
if (w) {
w = 0;
i.removeClass(css).data('w',0).val('');
}
It first makes sure w evaluates to true, and if it is, it checks if w=0 is not true (w != 0). If this is also true, then it goes on to the actual command.
This is common shorthand in a lot of languages that use lazy evaluation: If the next evaluation is put in with and (&&) then the following commands will not be executed if it returns false. This is useful in the sort of situations where you only want to perform an action on something if the previous statement returns true, like:
if (object != null && object.property == true)
to make sure object isn't null before using it, otherwise you would be accessing a null pointer.

Related

Execute query in portions and return values jQuery php [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
I'm using JSLint to go through JavaScript, and it's returning many suggestions to replace == (two equals signs) with === (three equals signs) when doing things like comparing idSele_UNVEHtype.value.length == 0 inside of an if statement.
Is there a performance benefit to replacing == with ===?
Any performance improvement would be welcomed as many comparison operators exist.
If no type conversion takes place, would there be a performance gain over ==?
The strict equality operator (===) behaves identically to the abstract equality operator (==) except no type conversion is done, and the types must be the same to be considered equal.
Reference: Javascript Tutorial: Comparison Operators
The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. Both are equally quick.
To quote Douglas Crockford's excellent JavaScript: The Good Parts,
JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. These are some of the interesting cases:
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
' \t\r\n ' == 0 // true
The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use === and !==. All of the comparisons just shown produce false with the === operator.
Update:
A good point was brought up by #Casebash in the comments and in #Phillipe Laybaert's answer concerning objects. For objects, == and === act consistently with one another (except in a special case).
var a = [1,2,3];
var b = [1,2,3];
var c = { x: 1, y: 2 };
var d = { x: 1, y: 2 };
var e = "text";
var f = "te" + "xt";
a == b // false
a === b // false
c == d // false
c === d // false
e == f // true
e === f // true
The special case is when you compare a primitive with an object that evaluates to the same primitive, due to its toString or valueOf method. For example, consider the comparison of a string primitive with a string object created using the String constructor.
"abc" == new String("abc") // true
"abc" === new String("abc") // false
Here the == operator is checking the values of the two objects and returning true, but the === is seeing that they're not the same type and returning false. Which one is correct? That really depends on what you're trying to compare. My advice is to bypass the question entirely and just don't use the String constructor to create string objects from string literals.
Reference
http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3
Using the == operator (Equality)
true == 1; //true, because 'true' is converted to 1 and then compared
"2" == 2; //true, because "2" is converted to 2 and then compared
Using the === operator (Identity)
true === 1; //false
"2" === 2; //false
This is because the equality operator == does type coercion, meaning that the interpreter implicitly tries to convert the values before comparing.
On the other hand, the identity operator === does not do type coercion, and thus does not convert the values when comparing.
Here's an interesting visualisation of the equality comparison between == and ===.
Source: https://github.com/dorey/JavaScript-Equality-Table (demo, unified demo)
var1 === var2
When using === for JavaScript equality testing, everything is as is.
Nothing gets converted before being evaluated.
var1 == var2
When using == for JavaScript equality testing, some funky conversions take place.
Summary of equality in Javascript
Conclusion:
Always use ===, unless you fully understand the funky conversions that take place with ==.
In the answers here, I didn't read anything about what equal means. Some will say that === means equal and of the same type, but that's not really true. It actually means that both operands reference the same object, or in case of value types, have the same value.
So, let's take the following code:
var a = [1,2,3];
var b = [1,2,3];
var c = a;
var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true
The same here:
var a = { x: 1, y: 2 };
var b = { x: 1, y: 2 };
var c = a;
var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true
Or even:
var a = { };
var b = { };
var c = a;
var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true
This behavior is not always obvious. There's more to the story than being equal and being of the same type.
The rule is:
For value types (numbers):
a === b returns true if a and b have the same value and are of the same type
For reference types:
a === b returns true if a and b reference the exact same object
For strings:
a === b returns true if a and b are both strings and contain the exact same characters
Strings: the special case...
Strings are not value types, but in Javascript they behave like value types, so they will be "equal" when the characters in the string are the same and when they are of the same length (as explained in the third rule)
Now it becomes interesting:
var a = "12" + "3";
var b = "123";
alert(a === b); // returns true, because strings behave like value types
But how about this?:
var a = new String("123");
var b = "123";
alert(a === b); // returns false !! (but they are equal and of the same type)
I thought strings behave like value types? Well, it depends who you ask... In this case a and b are not the same type. a is of type Object, while b is of type string. Just remember that creating a string object using the String constructor creates something of type Object that behaves as a string most of the time.
Let me add this counsel:
If in doubt, read the specification!
ECMA-262 is the specification for a scripting language of which JavaScript is a dialect. Of course in practice it matters more how the most important browsers behave than an esoteric definition of how something is supposed to be handled. But it is helpful to understand why new String("a") !== "a".
Please let me explain how to read the specification to clarify this question. I see that in this very old topic nobody had an answer for the very strange effect. So, if you can read a specification, this will help you in your profession tremendously. It is an acquired skill. So, let's continue.
Searching the PDF file for === brings me to page 56 of the specification: 11.9.4. The Strict Equals Operator ( === ), and after wading through the specificationalese I find:
11.9.6 The Strict Equality Comparison Algorithm
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
  1. If Type(x) is different from Type(y), return false.
  2. If Type(x) is Undefined, return true.
  3. If Type(x) is Null, return true.
  4. If Type(x) is not Number, go to step 11.
  5. If x is NaN, return false.
  6. If y is NaN, return false.
  7. If x is the same number value as y, return true.
  8. If x is +0 and y is −0, return true.
  9. If x is −0 and y is +0, return true.
  10. Return false.
  11. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.
  12. If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
  13. Return true if x and y refer to the same object or if they refer to objects joined to each other (see 13.1.2). Otherwise, return false.
Interesting is step 11. Yes, strings are treated as value types. But this does not explain why new String("a") !== "a". Do we have a browser not conforming to ECMA-262?
Not so fast!
Let's check the types of the operands. Try it out for yourself by wrapping them in typeof(). I find that new String("a") is an object, and step 1 is used: return false if the types are different.
If you wonder why new String("a") does not return a string, how about some exercise reading a specification? Have fun!
Aidiakapi wrote this in a comment below:
From the specification
11.2.2 The new Operator:
If Type(constructor) is not Object, throw a TypeError exception.
With other words, if String wouldn't be of type Object it couldn't be used with the new operator.
new always returns an Object, even for String constructors, too. And alas! The value semantics for strings (see step 11) is lost.
And this finally means: new String("a") !== "a".
I tested this in Firefox with Firebug using code like this:
console.time("testEquality");
var n = 0;
while (true) {
n++;
if (n == 100000)
break;
}
console.timeEnd("testEquality");
and
console.time("testTypeEquality");
var n = 0;
while (true) {
n++;
if (n === 100000)
break;
}
console.timeEnd("testTypeEquality");
My results (tested five times each and averaged):
==: 115.2
===: 114.4
So I'd say that the miniscule difference (this is over 100000 iterations, remember) is negligible. Performance isn't a reason to do ===. Type safety (well, as safe as you're going to get in JavaScript), and code quality is.
In PHP and JavaScript, it is a strict equality operator. Which means, it will compare both type and values.
In JavaScript it means of the same value and type.
For example,
4 == "4" // will return true
but
4 === "4" // will return false
Why == is so unpredictable?
What do you get when you compare an empty string "" with the number zero 0?
true
Yep, that's right according to == an empty string and the number zero are the same time.
And it doesn't end there, here's another one:
'0' == false // true
Things get really weird with arrays.
[1] == true // true
[] == false // true
[[]] == false // true
[0] == false // true
Then weirder with strings
[1,2,3] == '1,2,3' // true - REALLY?!
'\r\n\t' == 0 // true - Come on!
It get's worse:
When is equal not equal?
let A = '' // empty string
let B = 0 // zero
let C = '0' // zero string
A == B // true - ok...
B == C // true - so far so good...
A == C // **FALSE** - Plot twist!
Let me say that again:
(A == B) && (B == C) // true
(A == C) // **FALSE**
And this is just the crazy stuff you get with primitives.
It's a whole new level of crazy when you use == with objects.
At this point your probably wondering...
Why does this happen?
Well it's because unlike "triple equals" (===) which just checks if two values are the same.
== does a whole bunch of other stuff.
It has special handling for functions, special handling for nulls, undefined, strings, you name it.
It get's pretty wacky.
In fact, if you tried to write a function that does what == does it would look something like this:
function isEqual(x, y) { // if `==` were a function
if(typeof y === typeof x) return y === x;
// treat null and undefined the same
var xIsNothing = (y === undefined) || (y === null);
var yIsNothing = (x === undefined) || (x === null);
if(xIsNothing || yIsNothing) return (xIsNothing && yIsNothing);
if(typeof y === "function" || typeof x === "function") {
// if either value is a string
// convert the function into a string and compare
if(typeof x === "string") {
return x === y.toString();
} else if(typeof y === "string") {
return x.toString() === y;
}
return false;
}
if(typeof x === "object") x = toPrimitive(x);
if(typeof y === "object") y = toPrimitive(y);
if(typeof y === typeof x) return y === x;
// convert x and y into numbers if they are not already use the "+" trick
if(typeof x !== "number") x = +x;
if(typeof y !== "number") y = +y;
// actually the real `==` is even more complicated than this, especially in ES6
return x === y;
}
function toPrimitive(obj) {
var value = obj.valueOf();
if(obj !== value) return value;
return obj.toString();
}
So what does this mean?
It means == is complicated.
Because it's complicated it's hard to know what's going to happen when you use it.
Which means you could end up with bugs.
So the moral of the story is...
Make your life less complicated.
Use === instead of ==.
The End.
The === operator is called a strict comparison operator, it does differ from the == operator.
Lets take 2 vars a and b.
For "a == b" to evaluate to true a and b need to be the same value.
In the case of "a === b" a and b must be the same value and also the same type for it to evaluate to true.
Take the following example
var a = 1;
var b = "1";
if (a == b) //evaluates to true as a and b are both 1
{
alert("a == b");
}
if (a === b) //evaluates to false as a is not the same type as b
{
alert("a === b");
}
In summary; using the == operator might evaluate to true in situations where you do not want it to so using the === operator would be safer.
In the 90% usage scenario it won't matter which one you use, but it is handy to know the difference when you get some unexpected behaviour one day.
=== checks same sides are equal in type as well as value.
Example:
'1' === 1 // will return "false" because `string` is not a `number`
Common example:
0 == '' // will be "true", but it's very common to want this check to be "false"
Another common example:
null == undefined // returns "true", but in most cases a distinction is necessary
Many times an untyped check would be handy because you do not care if the value is either undefined, null, 0 or ""
Javascript execution flow diagram for strict equality / Comparison '==='
Javascript execution flow diagram for non strict equality / comparison '=='
JavaScript === vs == .
0==false // true
0===false // false, because they are of a different type
1=="1" // true, auto type coercion
1==="1" // false, because they are of a different type
It means equality without type coercion
type coercion means JavaScript do not automatically convert any other data types to string data types
0==false // true,although they are different types
0===false // false,as they are different types
2=='2' //true,different types,one is string and another is integer but
javaScript convert 2 to string by using == operator
2==='2' //false because by using === operator ,javaScript do not convert
integer to string
2===2 //true because both have same value and same types
In a typical script there will be no performance difference. More important may be the fact that thousand "===" is 1 KB heavier than thousand "==" :) JavaScript profilers can tell you if there is a performance difference in your case.
But personally I would do what JSLint suggests. This recommendation is there not because of performance issues, but because type coercion means ('\t\r\n' == 0) is true.
The equal comparison operator == is confusing and should be avoided.
If you HAVE TO live with it, then remember the following 3 things:
It is not transitive: (a == b) and (b == c) does not lead to (a == c)
It's mutually exclusive to its negation: (a == b) and (a != b) always hold opposite Boolean values, with all a and b.
In case of doubt, learn by heart the following truth table:
EQUAL OPERATOR TRUTH TABLE IN JAVASCRIPT
Each row in the table is a set of 3 mutually "equal" values, meaning that any 2 values among them are equal using the equal == sign*
** STRANGE: note that any two values on the first column are not equal in that sense.**
'' == 0 == false // Any two values among these 3 ones are equal with the == operator
'0' == 0 == false // Also a set of 3 equal values, note that only 0 and false are repeated
'\t' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\r' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\n' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\t\r\n' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
null == undefined // These two "default" values are not-equal to any of the listed values above
NaN // NaN is not equal to any thing, even to itself.
There is unlikely to be any performance difference between the two operations in your usage. There is no type-conversion to be done because both parameters are already the same type. Both operations will have a type comparison followed by a value comparison.
Simply
== means comparison between operands with type coercion
and
=== means comparison between operands without type coercion.
Type coercion in JavaScript means automatically converting data types to other data types.
For example:
123 == "123" // Returns true, because JS coerces string "123" to number 123
// and then goes on to compare `123 == 123`.
123 === "123" // Returns false, because JS does not coerce values of different types here.
Yes! It does matter.
=== operator in javascript checks value as well as type where as == operator just checks the value (does type conversion if required).
You can easily test it. Paste following code in an HTML file and open it in browser
<script>
function onPageLoad()
{
var x = "5";
var y = 5;
alert(x === 5);
};
</script>
</head>
<body onload='onPageLoad();'>
You will get 'false' in alert. Now modify the onPageLoad() method to alert(x == 5); you will get true.
As a rule of thumb, I would generally use === instead of == (and !== instead of !=).
Reasons are explained in in the answers above and also Douglas Crockford is pretty clear about it (JavaScript: The Good Parts).
However there is one single exception:
== null is an efficient way to check for 'is null or undefined':
if( value == null ){
// value is either null or undefined
}
For example jQuery 1.9.1 uses this pattern 43 times, and the JSHint syntax checker even provides the eqnull relaxing option for this reason.
From the jQuery style guide:
Strict equality checks (===) should be used in favor of ==. The only
exception is when checking for undefined and null by way of null.
// Check for both undefined and null values, for some important reason.
undefOrNull == null;
EDIT 2021-03:
Nowadays most browsers
support the Nullish coalescing operator (??)
and the Logical nullish assignment (??=), which allows a more concise way to
assign a default value if a variable is null or undefined, for example:
if (a.speed == null) {
// Set default if null or undefined
a.speed = 42;
}
can be written as any of these forms
a.speed ??= 42;
a.speed ?? a.speed = 42;
a.speed = a.speed ?? 42;
It's a strict check test.
It's a good thing especially if you're checking between 0 and false and null.
For example, if you have:
$a = 0;
Then:
$a==0;
$a==NULL;
$a==false;
All returns true and you may not want this. Let's suppose you have a function that can return the 0th index of an array or false on failure. If you check with "==" false, you can get a confusing result.
So with the same thing as above, but a strict test:
$a = 0;
$a===0; // returns true
$a===NULL; // returns false
$a===false; // returns false
=== operator checks the values as well as the types of the variables for equality.
== operator just checks the value of the variables for equality.
JSLint sometimes gives you unrealistic reasons to modify stuff. === has exactly the same performance as == if the types are already the same.
It is faster only when the types are not the same, in which case it does not try to convert types but directly returns a false.
So, IMHO, JSLint maybe used to write new code, but useless over-optimizing should be avoided at all costs.
Meaning, there is no reason to change == to === in a check like if (a == 'test') when you know it for a fact that a can only be a String.
Modifying a lot of code that way wastes developers' and reviewers' time and achieves nothing.
A simple example is
2 == '2' -> true, values are SAME because of type conversion.
2 === '2' -> false, values are NOT SAME because of no type conversion.
The top 2 answers both mentioned == means equality and === means identity. Unfortunately, this statement is incorrect.
If both operands of == are objects, then they are compared to see if they are the same object. If both operands point to the same object, then the equal operator returns true. Otherwise,
the two are not equal.
var a = [1, 2, 3];
var b = [1, 2, 3];
console.log(a == b) // false
console.log(a === b) // false
In the code above, both == and === get false because a and b are not the same objects.
That's to say: if both operands of == are objects, == behaves same as ===, which also means identity. The essential difference of this two operators is about type conversion. == has conversion before it checks equality, but === does not.
The problem is that you might easily get into trouble since JavaScript have a lot of implicit conversions meaning...
var x = 0;
var isTrue = x == null;
var isFalse = x === null;
Which pretty soon becomes a problem. The best sample of why implicit conversion is "evil" can be taken from this code in MFC / C++ which actually will compile due to an implicit conversion from CString to HANDLE which is a pointer typedef type...
CString x;
delete x;
Which obviously during runtime does very undefined things...
Google for implicit conversions in C++ and STL to get some of the arguments against it...
From the core javascript reference
=== Returns true if the operands are strictly equal (see above)
with no type conversion.
Equality comparison:
Operator ==
Returns true, when both operands are equal. The operands are converted to the same type before being compared.
>>> 1 == 1
true
>>> 1 == 2
false
>>> 1 == '1'
true
Equality and type comparison:
Operator ===
Returns true if both operands are equal and of the same type. It's generally
better and safer if you compare this way, because there's no behind-the-scenes type conversions.
>>> 1 === '1'
false
>>> 1 === 1
true
Here is a handy comparison table that shows the conversions that happen and the differences between == and ===.
As the conclusion states:
"Use three equals unless you fully understand the conversions that take
place for two-equals."
http://dorey.github.io/JavaScript-Equality-Table/
null and undefined are nothingness, that is,
var a;
var b = null;
Here a and b do not have values. Whereas, 0, false and '' are all values. One thing common beween all these are that they are all falsy values, which means they all satisfy falsy conditions.
So, the 0, false and '' together form a sub-group. And on other hand, null & undefined form the second sub-group. Check the comparisons in the below image. null and undefined would equal. The other three would equal to each other. But, they all are treated as falsy conditions in JavaScript.
This is same as any object (like {}, arrays, etc.), non-empty string & Boolean true are all truthy conditions. But, they are all not equal.

Javascript simplified if-statement

I'm scratching my head trying to understand this very simplified if statement. When searching for the answer, all I find is answers related to ternary operators.
Anyway. Why is it that the first case below works, while the latter throws an ReferenceError? Just trying to understand how things work.
true && alert("test")
var x;
true && x = 10;
This has to do with operator precedence. As the && operation is computed before the =, your second example would end up making no sense : (true && x) = 10;
For your second case to work, add parenthesis this way :
var x;
true && (x = 10);
Javascript seems to give higher precedence to && than to the assignment operator. The second line you gave is parsed as:
(true && x) = 10;
If you add parenthesis around the assignment, I think you will see the behavior that you were expecting:
true && (x = 10); // Sets x to 10 and the whole expression evaluates to 10.
And just in case you needed a pointer as to why && can be used as an if-statement, the phrase "short-circuit evaluation" might help.
It'a Operator precedence.
As you can see && has higher priority than =
So true && x = 10; is actually (true && x) = 10; which is clearly wrong. You can only assign value to variables, and (true && x) is either false or the value of x.
The result of alert() is undefined. So first example could be retyped as:
var x; // x is now 'undefined'
true && x; // true and undefined is undefined
The second example is about operators priorities. Runtime evaluate expression as (true && x) = 10;
var x;
true && (x = 10); // result will be 10

Lost in javascript comparisons

I'm writing a script to be executed when my body element hasn't got any of the following classes:
a OR b OR c AND d
I tried this, but it doesn't seem to do the trick:
if ((!$('body').hasClass('a')) || (!$('body').hasClass('b')) || ((!($('body').hasClass('c')) && (!$('body').hasClass('d'))))) {
}
UPDATE
This seems to work:
if (!($('body').hasClass('a') || $('body').hasClass('b') || $('body').hasClass('c') && $('body').hasClass('d'))) {
}
use
$(function(){
if ((!$('body').hasClass('a')) || (!$('body').hasClass('b')) || !($('body').hasClass('c') && $('body').hasClass('d'))) {
}
});
You are looking for a body that doesnt have any of the classes, so you need to use &&. Heres what happens:
if(hasclass(a) || hasclass(b)) = if(true OR false) = if(true)
Above the OR operator || means that once it hits a true evaluation, it will execute your if-block.
if(hasclass(a) && hasclass(b)) = if(true AND false) = if(false)
Here the AND operator && means that once you hit a false evaluation, you block won't be executed.
You want the last thing to happen, since you want it to have neither of the classes. Learn how to play with these operators as they can be very confusing. As long as you remember that the AND operator will execute only if all statements are true and the OR operator will only execute if one of the statements is true. Nested operators work the same, so if((a = b && b = c) || (a = c)) will execute if a,b and c are the same OR when a and c are the same, but not when a and b are the same or a and c are the same.
More on expression and operators (specifically Bitwise and a must read): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Bitwise_operators

Multiple OR conditions for an IF statement

Am I doing the multiple OR conditions for an IF statement the right way?
var A0minWidth = 841;
var A0minHeight = 1189;
var A0minWidthBleed = 847;
var A0minHeightBleed = 1195;
UploadedDocNameHeightMM = //(get it from the database)
UploadedDocNameWidthMM = //(get it from the database)
if(UploadedDocNameHeightMM < parseFloat(A0minHeight) || UploadedDocNameWidthMM < parseFloat(A0minWidth) || UploadedDocNameWidthMM > parseFloat(A0minWidthBleed) || UploadedDocNameHeightMM > parseFloat(A0minHeightBleed))
{
//do this
alert ("Yes! one of those.")
}
Help!
It depends on what your code is supposed to do of course, but syntactically this is correct - e.g. no need to wrap each each expression that is an operand to the logical-OR operators in parentheses like this:
if ((UploadedDocNameHeightMM < parseFloat(A0minHeight)) || (UploadedDocNameWidthMM < parseFloat(A0minWidth)) || (UploadedDocNameWidthMM > parseFloat(A0minWidthBleed)) || (UploadedDocNameHeightMM > parseFloat(A0minHeightBleed)))
{
alert("Yes! one of those.");
}
Also, the || operator will short-circuit evaluate. Basically it will not evaluate expressions to the right of any expression that evaluates to true.
For more information on || and other JavaScript logical operators including examples check out Mozilla's overview or search on JavaScript logical operators.
The syntax is correct.
However:
parseFloat is not necessary here
Are you sure the two first tests are correct (==> Don't you need to check if UploadedDocNameHeightMM > A0minHeight instead of < ?)

Is there anyway to implement XOR in javascript

I'm trying to implement XOR in javascript in the following way:
// XOR validation
if ((isEmptyString(firstStr) && !isEmptyString(secondStr)) ||
(!isEmptyString(firstStr) && isEmptyString(secondStr))
{
alert(SOME_VALIDATION_MSG);
return;
}
Is there a better way to do this in javascript?
Thanks.
As others have pointed out, logical XOR is the same as not-equal for booleans, so you can do this:
// XOR validation
if( isEmptyString(firstStr) != isEmptyString(secondStr) )
{
alert(SOME_VALIDATION_MSG);
return;
}
I pretend that you are looking for a logical XOR, as javascript already has a bitwise one (^) :)
I usually use a simple ternary operator (one of the rare times I use one):
if ((isEmptyString(firstStr) ? !isEmptyString(secondStr)
: isEmptyString(secondStr))) {
alert(SOME_VALIDATION_MSG);
return;
}
Edit:
working on the #Jeff Meatball Yang solution
if ((!isEmptyString(firstStr) ^ !isEmptyString(secondStr))) {
alert(SOME_VALIDATION_MSG);
return;
}
you negate the values in order to transform them in booleans and then apply the bitwise xor operator. Maybe it is not so maintainable as the first solution (or maybe I'm too accustomed to the first one)
You are doing an XOR of boolean values which is easy to model into a bitwise XOR (which Javascript has):
var a = isEmptyString(firstStr) ? 1 : 0;
var b = isEmptyString(secondStr) ? 1 : 0;
if(a ^ b) { ... }
http://www.howtocreate.co.uk/xor.html
You could use the bitwise XOR operator (^) directly:
if (isEmptyString(firstStr) ^ isEmptyString(secondStr)) {
// ...
}
It will work for your example since the boolean true and false values are converted into 1 and 0 because the bitwise operators work with 32-bit integers.
That expression will return also either 0 or 1, and that value will be coerced back to Boolean by the if statement.
You should be aware of the type coercion that occurs with the above approach, if you are looking for good performance, I wouldn't recommend you to work with the bitwise operators, you could also make a simple function to do it using only Boolean logical operators:
function xor(x, y) {
return (x || y) && !(x && y);
}
if (xor(isEmptyString(firstStr), isEmptyString(secondStr))) {
// ...
}
Easier one method:
if ((x+y) % 2) {
//statement
}
assuming of course that both variables are true booleans, that is, 1 or 0.
If x === y you'll get an even number, so XOR will be 0.
And if x !== y then you'll get an odd number, so XOR will be 1 :)
A second option, if you notice that x != y evaluates as a XOR, then all you must do is
if (x != y) {
//statement
}
Which will just evaluate, again, as a XOR. (I like this much better)
Of course, a nice idea would be to implement this into a function, but it's your choice only.
Hope any of the two methods help someone! I mark this answer as community wiki, so it can be improved.
Checkout this explanation of different implementations of XOR in javascript.
Just to summarize a few of them right here:
if( ( isEmptyString(firstStr) || isEmptyString(secondStr)) && !( isEmptyString(firstStr) && isEmptyString(secondStr)) ) {
alert(SOME_VALIDATION_MSG);
return;
}
OR
if( isEmptyString(firstStr)? !isEmptyString(secondStr): isEmptyString(secondStr)) {
alert(SOME_VALIDATION_MSG);
return;
}
OR
if( (isEmptyString(firstStr) ? 1 : 0 ) ^ (isEmptyString(secondStr) ? 1 : 0 ) ) {
alert(SOME_VALIDATION_MSG);
return;
}
OR
if( !isEmptyString(firstStr)!= !isEmptyString(secondStr)) {
alert(SOME_VALIDATION_MSG);
return;
}
Quoting from this article:
Unfortunately, JavaScript does not have a logical XOR operator.
You can "emulate" the behaviour of the XOR operator with something like:
if( !foo != !bar ) {
...
}
The linked article discusses a couple of alternative approaches.
XOR just means "are these two boolean values different?". Therefore:
if (!!isEmptyString(firstStr) != !!isEmptyString(secondStr)) {
// ...
}
The !!s are just to guarantee that the != operator compares two genuine boolean values, since conceivably isEmptyString() returns something else (like null for false, or the string itself for true).
Assuming you are looking for the BOOLEAN XOR, here is a simple implementation.
function xor(expr1, expr2){
return ((expr1 || expr2) && !(expr1 && expr2));
}
The above derives from the definition of an "exclusive disjunction" {either one, but not both}.
Since the boolean values true and false are converted to 1 and 0 respectively when using bitwise operators on them, the bitwise-XOR ^ can do double-duty as a logical XOR as well as a bitwiseone, so long as your values are boolean values (Javascript's "truthy" values wont work). This is easy to acheive with the negation ! operator.
a XOR b is logially equivalent to the following (short) list of expressions:
!a ^ !b;
!a != !b;
There are plenty of other forms possible - such as !a ? !!b : !b - but these two patterns have the advantage of only evaluating a and b once each (and will not "short-circuit" too if a is false and thus not evaluate b), while forms using ternary ?:, OR ||, or AND && operators will either double-evaluate or short-circuit.
The negation ! operators in both statements is important to include for a couple reasons: it converts all "truthy" values into boolean values ( "" -> false, 12 -> true, etc.) so that the bitwise operator has values it can work with, so the inequality != operator only compares each expression's truth value (a != b would not work properly if a or b were non-equal, non-empty strings, etc.), and so that each evaluation returns a boolean value result instead of the first "truthy" value.
You can keep expanding on these forms by adding double negations (or the exception, !!a ^ !!b, which is still equivalent to XOR), but be careful when negating just part of the expression. These forms may seem at first glance to "work" if you're thinking in terms of distribution in arithmatic (where 2(a + b) == 2a + 2b, etc.), but in fact produce different truth tables from XOR (these produce similar results to logical NXOR):
!( a ^ b )
!( !!a ^ !!b )
!!a == !!b
The general form for XOR, then, could be the function (truth table fiddle):
function xor( a, b ) { return !a ^ !b; }
And your specific example would then be:
if ( xor( isEmptyString( firstStr ), isEmptyString( secondStr ) ) ) { ... }
Or if isEmptyString returns only boolean values and you don't want a general xor function, simply:
if ( isEmptyString( firstStr ) ^ isEmptyString( secondStr ) ) { ... }
Javascript does not have a logical XOR operator, so your construct seems plausible. Had it been numbers then you could have used ^ i.e. bitwise XOR operator.
cheers
here's an XOR that can accommodate from two to many arguments
function XOR() {
for (var i = 1; i < arguments.length; i++)
if ( arguments[0] != arguments[i] )
return false;
return true;
}
Example of use:
if ( XOR( isEmptyString(firstStr), isEmptyString(secondStr) ) ) {
alert(SOME_VALIDATION_MSG);
return;
}
I hope this will be the shortest and cleanest one
function xor(x,y){return true==(x!==y);}
This will work for any type
Here is an XOR function that takes a variable number of arguments (including two). The arguments only need to be truthy or falsy, not true or false.
function xor() {
for (var i=arguments.length-1, trueCount=0; i>=0; --i)
if (arguments[i])
++trueCount;
return trueCount & 1;
}
On Chrome on my 2007 MacBook, it runs in 14 ns for three arguments. Oddly, this slightly different version takes 2935 ns for three arguments:
function xorSlow() {
for (var i=arguments.length-1, result=false; i>=0; --i)
if (arguments[i])
result ^= true;
return result;
}
Try this:
function xor(x,y)
var result = x || y
if (x === y) {
result = false
}
return result
}
There's a few methods, but the ternary method (a ? !b : b) appears to perform best. Also, setting Boolean.prototype.xor appears to be an option if you need to xor things often.
http://jsperf.com/xor-implementations
You could do this:
Math.abs( isEmptyString(firstStr) - isEmptyString(secondStr) )
The result of that is the result of a XOR operation.
#george, I like your function for its capability to take in more than 2 operands. I have a slight improvement to make it return faster:
function xor() {
for (var i=arguments.length-1, trueCount=0; i>=0; --i)
if (arguments[i]) {
if (trueCount)
return false
++trueCount;
}
return trueCount & 1;
}

Categories

Resources