Inverse comparison/equals arguments [duplicate] - javascript

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.

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.

Is there a more compact option to check if a variable equals "this" OR "that"? [duplicate]

This question already has answers here:
Concise way to compare against multiple values [duplicate]
(8 answers)
Closed 4 years ago.
I want to check if a variable (in this case sampleVariable) is equal to THIS or THAT:
if(sampleVariable == "THIS" || chosenVerb == "THAT")
The above code should work fine, but I was wondering if there was a way to simplify and compact it - for example, something like this (this probably isn't how you do it, just an example):
if(sampleVariable == "THIS" || "THAT")
I'm fairly certain the above doesn't work since it will check for the two statements being true separately.
I found this website, which seems to be what I'm looking for. They say that this code is the best way to go around it:
if (fruit.match(/^(banana|lemon|mango|pineapple)$/)) {
handleYellowFruit();
}
Is this still the way that this is supposed to be done (since the blog post I linked above was published over half a decade ago)? If so, what are these characters in the parentheses: / ^ $ ?
Thanks for the help!
Depending on browser support and ability to polyfill, I'd try array.includes:
if ((["THIS", "THAT"]).includes(sampleVariable)) {

Not not (!!) inside if condition [duplicate]

This question already has answers here:
Why is the !! preferable in checking if an object is true? [duplicate]
(3 answers)
Closed 7 years ago.
Note: it's actually a duplicate of What is the difference between if(!!condition) and if(condition)
While I understand what the !! means (double not), for this same reason it doesn't make sense to me its use in the MDN documentation:
if (!!window.Worker) {
...
}
Isn't this exactly the same as this for this situation?
if (window.Worker) {
...
}
The casting to boolean makes no sense for me since the if will only be executed if the window.Worker exists. To say that it's True or Object for an if() conditional (I think) is the same.
So, why is the !! used here? Or, why is the window.Worker casted to boolean inside an if()?
Yes it is exactly the same. Nothing to add.
It might have been used to emphasize that the window.Worker property - expected to be a function - is cast to a boolean for detecting its presence, instead of looking like a forgotten () call. Regardless, it is now gone.

comma inside if statment in javascript [duplicate]

This question already has answers here:
Why does javascript accept commas in if statements?
(5 answers)
Closed 8 years ago.
I've searched in SO but I didn't find something similar. Maybe I am using wrong search keys.
I was editing a javascript library when I found this if statment
var a = location.hash.replace(/^#/, "");
if (container = $("#content"), a) {
..content
} else {
...other code
}
the first part container = $("#content") is assigning the value of $("#content") to container but I don't understand why there is a comma inside the If. Is it like an AND operator?
Something like if (container = $("#content") && a) ?
What is it evaluating?
The comma operator in JavaScript is pretty similar to the concept in other C-like languages. It's a way of stringing multiple expressions together into one (syntactic) expression. The value of the whole thing is the value of the last expression in the list.
Thus in this case, container = $("#content") is evaluated, and then a is evaluated. The value of the whole thing is the value of a.
A good question is why that code was written that way. There are times when the comma operator is useful, but usually it's just a way to save some typing and make code a little more concise.
It is comma operator.
Basically its doing two things. First there is assignment and then the , just evaluates a and validates against it in the if condition.

Javascript comparison operators order [duplicate]

This question already has answers here:
Why Constant first in an if condition [duplicate]
(2 answers)
Closed 8 years ago.
I saw a couple of times code like "expected" === variable instead of variable === "expected".
Why is that? Is it performance or readability related? I personally find it more confusing and I always wondered why would someone write the string first, and then the variable in a comparison operation.
The main reason is to protect against a single equals typo causing assignment. Commonly known as Yoda Conditions (thanks Paul S in the comments).
E.g:
var i = 1;
if(i = 2) //no error, but unexpected behavior
if(2 = i) //error - invalid left hand side assignment.
The if(i=2) option would cause unexpected behaviour because it would assign 2 to i and also enter the if statement which could be a subtle bug that is hard to track down compared with receiving an error. This approach is even more useful for a compiled language such as C++ where the compiler will raise an error so you know about it during compile time. C# and Java compilers don't allow conditionals to be an assignment, so the ordering is of less value there.

Categories