Why Constant first in an if condition [duplicate] - javascript

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.

Related

Checking value with JavaScript [duplicate]

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.

How can I pass label value as variable for if else case? [duplicate]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I was trying to compare a variable to a value and accidently ended up using '=' in place of '==' hence the code looked like:
var test = 1;
if(test = 2) {
console.log(test);
}
instead of:
var test = 1;
if(test == 2) {
console.log(test);
}
I assume the value was successfully assigned to the variable , hence the condition returned truthy and console.log() was executed. Is my assumption correct? What is a good coding practice to avoid such mistakes besides Yoda Condition reference
Lint it. There are tools that can automatically analyze your Javascript and catch common errors like this.
The assignment operator (=) in JavaScript evaluates to the right-side value of the expression, which means that test = 2 evaluates to 2 and since all values that aren't falsey (0, false, null, undefined, '', NaN) are thruthy by definition, the if condition was entered.
A good practice would be to always use the === sign when checking for equality and !== for inequality and there are tools that will help you enforcing those rules, like JSHint
Use if (a === b) { do stuff ; } that's three equals, ===
In Javascript you often need three equals, ===, as this requires primitives to have both the same type and value, and will not perform type coercion which, although you don't mention it, can be another source of confusion.
If you leave off an equals, it becomes two equals comparison, a == b, which might not work quite as expected if you are a beginner or unaware of the quirks of this comparison in Javascript, but at least is not an assignment.
The answer in JavaScript is pretty easy: always use strict comparison. This will avoid not only assignment errors, but also some non-intuitive behavior that can come from JavaScript's weak comparison rules.
Edit: Didn't see the questioners requirement to avoid this method.
Use strict comparison operator (===). You can also change the order of the values being compared which will fail if you use assignment statement rather than comparison operator.
Fails:
var test = 1;
if(2 = test) {
console.log(test);
}
The above code will throw an exception since you can't assign a value to the constant value.
Works:
var test = 1;
if(2 == test) {
console.log(test);
}
a = b is an assignment. Meaning a will equal to b.
a == b is a comparison. Meaning does a equal to b.
a === b is the same as == however no type conversion is done. Meaning does a equal to b, but also is it the same object/type?
Where your going wrong with your code is
var test = 1;
if(test = 2) { //this is true, because test now equals 2.
console.log(test);
}
When you assign something the value returned isn't representative of whether or not the assignment was successful, it actually just returns the right hand side of the assignment (e.g, the test = 2 in if (test = 2) would return 2 which is "truthy" in JavaScript, thus causing console.log(test) to evaluate. This can actually be quite useful in certain cases. For example:
while ((value = retrieveSomeValue()) !== null) {
console.log(value);
}
The code above continually assigns some variable value to the result of some function retrieveSomeValue, tests the resulting value to make sure it isn't null, and executes the while body.
To answer your question though: The === operator is more easily distinguished from the = operator and probably behaves more like what you would expect out of ==. Which equals operator (== vs ===) should be used in JavaScript comparisons?

Javascript difference between "=" and "===" [duplicate]

This question already has answers here:
Difference between == and === in JavaScript [duplicate]
(2 answers)
Closed 7 years ago.
I struggle to understand the function below. I didn't know why my script wasn't working until I changed = with === in the if statement, as shown below. Why does === work while = doesn't?
var testTest = function(answer) {
if (answer === "doggies") {
return "My favorite animal!";
} else {
return "Tested";
}
};
testTest("doggies")
When I type doggies, it shows me My favorite animal! With anything else, it returns Tested as it should.
However, when I change the === in the if statement with =, the else part doesn't work.
var testTest = function(answer) {
if (answer = "doggies") {
return "My favorite animal!";
} else {
return "Tested";
}
};
testTest("elephant")
You need to use == or === for equality checking. = is the assignment operator.
You can read about assignment operators here on MDN.
As a quick reference as you are learning JS:
= assignment operator
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
I assume you know that = is for assignment, after all, you are using assignment already in the first line:
var testTest = function(answer) {
and I don't think you think that this would compare anything here (or do you?).
The question remains though, why does = in if (answer = "doggies") "not work"?
An assignment is an expression. The result of that expression is the value that was assigned. Here, the result of answer = "doggies" is "doggies", i.e. you essentially running if ("doggies").
JavaScript performs type coercion. That means it automatically converts values of one data type to values of a different data type if necessary, according to specific rules.
The condition of an if statement has to resolve to a Boolean value. But here you are using a string value as condition. The String -> Boolean conversion rules are pretty simple:
The empty string converts to false.
A non-empty string converts to true.
So, after type conversion, the statement is equivalent to if (true), hence it will always execute the first block, never the else block.

Inverse comparison/equals arguments [duplicate]

This question already has answers here:
Why Constant first in an if condition [duplicate]
(2 answers)
Checking for null - what order? [duplicate]
(8 answers)
Closed 8 years ago.
I saw many times in open source projects that folks write something like that:
if("" !== foo) {
// ...
}
Why on earth do they do that? I mean you are checking if foo's value is empty string or not. I understand that "" !== foo and foo !== "" means exactly the same. But what's the reason to write tricky and less obvious code?
I'm personally not a fan of this style, either; however, the style stems from this:
if (x = "") { // **oops**, meant to do "==" but ended up assigning to "x"
// ...
}
The "if" statement here will cause an unintended side-effect. There are a number of languages in which side effects and implicit conversions to boolean make it easy to shoot oneself in the foot this way (JavaScript and C++ come to mind). To avoid this, some have the convention of inverting the ordering, since assigning to a constant will produce a more immediate and obvious error. I'm personally not a fan of this, because it makes the code read less like English ("if x equals the empty string" reads more naturally than "if empty string equals x"), and better tooling (linters, source code analyzers, etc.) can catch these just as effectively.

How can jquery || "OR" be used outside of an if statement? [duplicate]

This question already has answers here:
JavaScript OR (||) variable assignment explanation
(12 answers)
What does the construct x = x || y mean?
(12 answers)
In Javascript, what does it mean when there is a logical operator in a variable declaration? [duplicate]
Closed 8 years ago.
I've never seen the OR paramater || used outside of an if statement.
What does this line of code do?
var doc = ($iframe[0].contentWindow || $iframe[0].contentDocument).document
Is it saying making it equal to either one of those???
A || B
evaluates A first. If it is true, A is returned, and B never needs to be looked at.
If A is false, B is evaluated and returned.
For example, if you write
function (x)
{ x = x || 50
...
This would make x=50, if x is nil (or some kind of false value).
Otherwise, x would not be changed.
It is like having a default value, or a failsafe protection. If you know that the answer should never be false, then if A is false, you provide a backup value of B.
A way to get a DOM reference to the iframe's window object is to use:
contentWindow.document
Now, cause IE<8 has problems with it, a small polyfill is to use
var doc = ($iframe[0].contentWindow || $iframe[0].contentDocument).document;
// Browser you get this one ^^^ ? NO? Sh** you're IE7, go with^^
So earlyer versions of IE will skip the contentWindow cause not recognized, and thanks to the || (or) operator will follow up with the next contentDocument.
I don't have to repeat what's the OR operator cause other smart people already explained it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
This is just a short form of the ternary operator, which always returns a value depending to a statement. So, e. g.:
var fruit = "apple";
var test = fruit === "apple" ? fruit : "banana";
This sets the variable test to the value of fruit, when fruit is set to "apple". Otherwise, test will be initialized with "banana".

Categories