I am currently having a hard time figuring out how to use multiple conditions for my if-else statements. I can do 1 condition at a time, but multiples are a problem for me. I'm not quite sure where to start with the multiple one as I'm using the HTML form stuff, and I'm not sure where to start with it as well. Any sample code is fine as I would like to learn rather than have people figure everything out for me.
Ok, let's start from the beginning.
You agree that this code right here:
if (true)
console.log('foo');
obviously prints out 'foo' on your console, cause the condition is satisfied (i.e. is true).
Let's try something different now:
if (true && false)
console.log('bar');
The && in Javascript and most programming languages is the and operator, which evaluates to true only if both the conditions at its left and at its right are true. This means that the code above does not print out 'bar'.
if (true || false)
console.log('bla');
The || operator, on the other hand, is the or operator, which is true when one of the two conditions (or both) is true. In this case, 'bla' is printed out on your console.
In the end, let's have a look at the ! operator (not): if the condition that follows the operator is true, then it evaluates to false, and viceversa. So writing if (!false) equals if (true).
Now you can apply these simple rules to easily use multiple logical conditions in one if or else branch. Remember the precedence of the logical operators, i.e. which one you have to evaluate first if you have more than one, taking a look here: Which Logic Operator Takes Precedence
Related
Does an "if" statement with multiple "or" operators exit when the first condition returns true, or are all conditions evaluated?
i.e. does the order of your conditions matter?
Example scenario:
A shouldComponentUpdate() function with an if statement and the evaluated conditions vary in cost.
Does the order of the conditions (with the least expensive first) promise an improvement in performance or will the entire if statement get evaluated even if the first condition will return a true?
For example:
Assume an if statement in the form:
if ( (this.props.value != nextProps.value) || (deepDiffer(object1, object2) )
If (this.props.value != nextProps.value) returns true, will the code still evaluate the deepDiffer? Or will it immediately enter the if statement and execute the conditional code?
This is Javascript, so yes, it exits when the first condition is true.
According to MDN:
As logical expressions are evaluated left to right, they are tested
for possible "short-circuit" evaluation using the following rules:
false && anything is short-circuit evaluated to false.
true || anything is short-circuit evaluated to true.
The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side
effects of doing so do not take effect.
In a condition, if there are multiple 'or', they are checked from left to right and if the first is true, it won't check the nexts.
Same behaviour in a 'and' chain, when the first false is encounter, the nexts won't be checked
This is basic Javascript
I ran into this piece of code:
<a ng-click= "item.statusId !== itemStatus.in || transfer()">
I guess we can generalize as:
<element ng-click = "someVar !== someValue || doStuff()">
I then found this article on short circuits and another more focused one once I knew what they are called. However, I still don't get it.
Does it basically work on the principle of an OR statement ending evaluation if the first statement evaluates to true? So if the first statement is true, end evaluation, if it's false, run the function in the second half of the OR statement? (This is the main question I am asking, everything else is extra).
I guess that part I don't get is whether the compiler interprets this code differently or it still evaluates to false and just runs the function. Not even sure how to phrase Q.
Does it basically work on the principle of an OR statement ending evaluation if the first statement evaluates to true? So if the first statement is true, end evaluation, if it's false, run the function in the second half of the OR statement?
It's effectively shorthand for an if statement, and you intuited correctly why it works. For more details on short-circuit evaluation in JavaScript, see this Stack Overflow question.
That code is equivalent to:
//Note the intentional and explicit use of `== false` to mean falsy (NOT `=== false` to indicate strict equality test for false)
if( (item.statusId !== itemStatus.in) == false ) {
transfer();
}
It is an interesting means of executing a function only when a condition is falsy.
There are many different examples of this around on StackOverflow, and is not specific to AngularJS.
I wrote a function that works great for mobile, based on something I found on SO a while ago.
jQuery(document).on('touchstart', function(event) {
if ( !jQuery(event.target).closest("#peopleMenu").length) {
jQuery("#peopleMenu").fadeOut();
}
});
the part that I found was in the "if" statement that took me a bit to wrap my head around.
It is saying that if the target touch event is on #peopleMenu , it will stay open, or close if touched off. The if statement boils down to :
if (!1) {
//false - understand this.
}
if (!0) {
//true - hmmm.
}
My question is basically is this a common programming paradigm, a strange js feature, or is it just trickier than it needs to be? Thanks.
This is common in many languages. Everything in JavaScript has an inherent Boolean value, generally known as either truthy or falsy.(e.g. 0 or an empty string). So in this case, if the length comes back as 0, the if statement is false. Here is a great writeup on this topic as it relates to Javascript if you care to know more: Truthy/Falsy
It is common, it mean if you touch something else than #peopleMenu or its childrens, do something.
0 is a falsy value while every other integer are truthy.
Using bang (!) reverse the value, !true == false and !false == true.
The .length property of jQuery is the way to know how many element are selected. 0 mean none.
I opened a js file that I wrote a while back and although it's working, I thought I spotted an error. (JS is not my primary language)
I had this:
if( myvar = fieldval.match(mypattern))
{
//Do Stuff
}
So I think I get it. Is this a correct statement?:
A javascript assignment operation evaluates to the value being assigned.
I tested on w3schools
<script type="text/javascript">
var str="The rain in SPAIN stays mainly in the plain";
var patt1=/ain/gi;
var test
document.write(test=str.match(patt1));
</script>
and it writes "ain,AIN,ain,ain" where I might have expected it to write "true" or not to write at all because boolean true is not a string. Is my line of thought and then ultimate conclusion correct. (I ask about my line of thought on this because I do not have a lot of formal CS training.)
It is a correct statement. The new value of myvar is tested:
if ( myvar = fieldval.match(mypattern) )
When the String.match method cannot find a match, it returns null. !!null === false, so the if-block is not evaluated. When any non-empty match is found, the condition is true, and the block is evaluated.
In this case, it is very likely that the if-statement is correct, and that the following is intended:
if ( (myvar = fieldval.match(mypattern)) !== null )
Rob W is correct, however it's extremely poor practice to put an assignment in an if statement like that. In the future, anyone coming along (including yourself) will scratch their head at that statement to determine if that's what you really meant.
I highly recommend Douglas Crockford's talk: http://www.youtube.com/watch?v=taaEzHI9xyY It'll make anyone (Js dev or not) a better developer for watching it because you'll consider the implications of your coding style and what future maintainers might assume.
match returns an array of matching values, not boolean. Use test instead.
The function string.match() returns an array of matches, or null if no matches are found. The code works because null evaluates to false in an if statement, while an array evaluates to true.
So indeed, the result of str.match is stored in myvar and then myvar is evaluated as boolean. It works as expected.
It seems that the strict equality operator is preferred whenever possible - I put my code in JSLint and got the following feedback.
Code:
function log() {
console.log(arguments.length == 1 ? arguments[0] : arguments);
}
Feedback from JSLint:
Problem at line 2 character 34: Expected '===' and instead saw '=='.
I am curious to know what advantages === has over == here. Basically, .length returns a Number, and 1 is a Number as well. You can be 100% sure, so === is just a redundant extra token. Also, checking for the type whilst you know the types will always be the same has no performance advantage either.
So what's actually the reason behind using === here?
The only reason is that you don't have to think whether the comparison you are doing will involve coercion or not. If you stick to using ===, you just have one thing less to worry about.
Of course not everyone agrees. This is why you can disable specific checks in JSlint, if you are sure of what you are doing.
It's not strictly required, as you know the length function is well-tested. But what if length was a bit buggy, and there was a chance it could return false?
In this situation, both 0 and false would be evaluated as false using the == comparison. To test for false (when there is also the chance of 0 being returned), you need to also check the data type, which is where === comes in.
Well, === is supposed to be infinitesimally faster, as it can fail faster (on type mismatch), but that's deep inside the "pointless microoptimizations" territory.
Realistically, I'd advise for ===, even if you are 105% sure - I've been tripped up by my assumptions too many times ("yes, I am positive they are the ... same ... uh ..."). Unless there's a good reason to turn them off, it is better to keep sanity checks enabled in code than trust to do them in your mind.