This question already has answers here:
What is "x && foo()"?
(5 answers)
Closed 8 years ago.
Let's say we have this function:
loadView : function(view) {
this.view && this.view.remove();
this.view = view;
}
What does the first line do? For example if the line was this.view && this.otherView, it would return true if both view and otherView exists and false if one of them doesn't, but now there is a function being called at the end, which is confusing me.
Is the first line equivalent to:
if(this.view) {this.view.remove()}
?
it's a short circuit evaluation.
If this.view is "falsey" then this.view.remove() will not be evaluated.
So the answer to your question is yes.
It's called a guard operator. You would usually use && in this way
if(thing1 === 1 && thing2 === 2){}
You'll notice we want to check if BOTH things return true. Well the way it works is that we know that 'thing 2 === 0' will never run if the first expression (thing1 === 1) doesn't evaluate to true. Why run the second expression if they both have to be true and the first one already failed. Taking that knowledge we can now use it as a guard to not run the second expression, unless the first expression it true, or in this case truthy.
So in your code, this.view.remove() only runs if this.view is truthy.
Related
This question already has answers here:
How does the single equal sign work in the if statement in javascript
(6 answers)
Closed 3 years ago.
This is my general code (in JavaScript):
let x = Math.floor(Math.random()×6)+1);
if (x=1){
do this
} else if (x=2){
do that
} else if.... and so on.
Whenever I test this code in a browser, only actions that could happen in the {do this} section happen. x is being locked as 1, even though it is meant to be a fair 6 sided die. Any ideas why this is happening, and how I can fix it?
The = operator in JavaScript is for assignment. x=1 will always return true because that is an assignment that will never fail. To test for equality use == (equality with conversion) or === (strict equality).
You have your if (x=1) assigning the value of 1 to x, rather than checking if it's equal to it. This results in it always returning TRUE. Using a pair of == (or ===) will solve this.
This question already has answers here:
Curly Brackets in Arrow Functions
(3 answers)
Closed 9 months ago.
I know this question falls in the realm of "basics", however I'd like to understand the inner workings of the language.
My question is:
Do operators 'return' the expression's value by default after evaluation?
'return' as in if we were to write:
//some operation using == < > etc...
return result;
There is a slight difference.
foo===bar does not return anything, it only calculates a boolean value.
You can combine this with a return statement, foo===bar to return true if foo == bar, and false otherwise.
if (foo === bar){return true} ONLY returns true if the two are equal, it would return nothing if foo does not equal bar.
This question already has answers here:
javascript multiple OR conditions in IF statement
(6 answers)
Closed 3 years ago.
if(eggsAmount < eggsMin || milkAmount < milkMin || flourAmount || FlourMin)
Does it mean whichever of these are true?
Yes, in an if statement with only OR || operators, it will simply go through each condition and as soon as it finds one that is true, the if statement resolves as true, the rest are not checked, and the code in the if block.
An if statement containing multiple OR conditions (||) has in Javascript the same behaviour descripted by Boolean Algebra: the whole evaluation is True if any of the conditions is true.
At this w3schools link you can find JS logic operators description.
Anyway the evaluation of the expression itself is not necessarily a boolean value. The expression
Res = expr1 || expr2 || ... || exprN
is evaluated as the first condition that can be evaluated as true (for example if expr1 is 4+7, Res=11.
If none of the condition can be evaluated as true the assigned value is the value contained in the last condition: Res = exprN.
(thanks to Jared Farrish, Barmar and Teemu)
This question already has answers here:
IF Statement Always True
(3 answers)
Closed 5 years ago.
I have the following code:
console.log(usernameExists);
if (usernameExists = true) {
console.log("returning true");
return true;
} else if (looped = true) {
console.log(usernameExists+" is returned");
looped = null;
return false;
}
The first console.log(usernameExists) is returning false, but still I am getting a console message of "returning true", and the function in which this is, is returning true! I simply can't figure this out.
The condition is always true, because you assign this value to the variable and this is the value which is evaluated for the if clause.
But you could use a direct check without a compare value (and without assigning this value).
Beside that, you could change the else part to only an if part, becaue you exit the function with return, so no more else happen in this case.
if (usernameExists) {
console.log("returning true");
return true;
}
if (looped) {
console.log(usernameExists+" is returned");
looped = null;
return false;
}
= is an assignment, so you're setting the variable to true, which itself makes the if statement true. What you want is to check if the variable is set to true. In order to do that, use the == or === operators.
For checking conditions, you need to use '==' operator. '=' means assignment operator.
Whereas a '===' checks for value and type.
Hope that is the issue.
In your conditions you are using a single equal!!!
Therefore, it is a assignation operation that is done instead of comparison! So you are not checking that your variable is equal to true but you are assigning it to true and since your assignement operation was successful your condition is at the same time fulfilled.
Change it with two or tree equals == or === instead of =
Usage and differences between == and === are explained very well here:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
This question already has answers here:
Order in conditional statements [duplicate]
(2 answers)
Closed 9 years ago.
I often see if structures being coded like this:
if (true == a)
if (false == a)
Why do they put the constant value first and not the variable? as in this example:
if (a == true)
if (b == true)
This is called yoda syntax or yoda conditions.
It is used to help prevent accidental assignments.
If you forget an equals sign it will fail
if(false = $a) fails to compile
if($a = true) assigns the value of true to the variable $a and evaluates as true
The Wordpress Coding Standards mention this specifically:
if ( true == $the_force ) {
$victorious = you_will( $be );
}
When doing logical comparisons, always put the variable on the right
side, constants or literals on the left.
In the above example, if you omit an equals sign (admit it, it happens
even to the most seasoned of us), you’ll get a parse error, because
you can’t assign to a constant like true. If the statement were the
other way around ( $the_force = true ), the assignment would be
perfectly valid, returning 1, causing the if statement to evaluate to
true, and you could be chasing that bug for a while.
A little bizarre, it is, to read. Get used to it, you will.
This is an example of YODA Style of coding
if (var a == true){
}
is less safer than
if (true == var a){
}
because when you forget that second = mark, you'll get an invalid assignment error, and can catch it at compile time.