Javascript comparison operators order [duplicate] - javascript

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.

Related

Does it matter on which side a value goes in a JavaScript expression? [duplicate]

This question already has answers here:
What is the difference between these (bCondition == NULL) and (NULL==bCondition)? [duplicate]
(6 answers)
Closed 5 years ago.
Recently, I came across a code like this:
if (0 === $something) { }
Is there any difference between the code above with:
if ($something === 0) { }
Actually there is no difference in both performance wise or in functional perspective. I can say it's a personal choice of coding style often called that as Yoda Style
In programming jargon, Yoda conditions (also called Yoda notation) is a programming style where the two parts of an expression are reversed in a conditional statement.
I prefer the later way as the first way kills the readability of code (at least for me)
No,
there is absolutely no difference between the two as the if condition will check for equality between both sides.

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)) {

Nested if's: is it better to use if (x) {statement;} or if (!x) return; statement; [duplicate]

This question already has answers here:
Is it better to wrap code into an 'IF' statement, or is it better to 'short circuit' the function and return? [closed]
(12 answers)
Closed 8 years ago.
Is it generally accepted to be better programming practice to use a structure like:
if (x == 1) {
if (y != 1) {
[code]
}
}
or to use a guard like this:
if (x == 1) {
if (y == 1) return;
[code]
}
The first style has a more logical structure, where it's clear at a glance which code depends on what.
But the second style results in a more simple visual style and fewer lines of code.
Is the second style considered a bad habit? Or is it just a style choice?
[update] this is a duplicate
Whatever your 'house style' says.
The thing with coding style is - it really doesn't matter, as long as it's consistent throughout your code. And the code of all your colleagues.
Clarity is king - if your code is clear what it's doing, it's good code. If it's not clear what it's doing, it's bad code. (and if everyone's using a different style, it's not going to be clear, and therefore all your code is bad). And that's all. Don't worry about saving lines of code - the compiler doesn't care.
The question should not be 'Is it better to use nested ifs or use guards' but 'When is it better to use nested ifs and when guards'!
There are pro's and con's in both ways.
Using ifs promotes single point of exit but can become difficult to read when nesting is deep.
Guards reduce nesting and easier to read but create multiple points of exit.
it does not matter which you chose as long as your functions are short!

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.

Javascript How do I force a string + variable to be evaluated as a variable [duplicate]

This question already has answers here:
is there a way to execute a function when I have its name in a string [duplicate]
(2 answers)
Closed 9 years ago.
Im not even sure how to word this and is probably why I am having trouble finding an answer in google.
When the code is run currentCardRow will equal 1 therefore it should be cardSelected1 which is what is shown in the console.log. I need it to go a step further because cardSelected1 is a variable and I need it to evaluate show in the console log as Invitation. Invitation is an example of a variable for cardSelected1.
I am not sure on what the correct syntax is to make this happen.
var currentCardSelected = "cardSelected" + currentCardRow;
Thanks for your help!
JavaScript has an Eval() function which allows you to evaluate strings as javascript code.
For example
var bar = "123";
var foo = "bar";
console.log(eval(foo));
will print "123" to the console.
For more information on eval, you can consult the MDN docs.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
Generally, the use of eval() is considered poor practice as it makes the code difficult to read. There are likely more elegant solutions to implement what you have described, however, eval will solve your current problem.
var currentCardSelected = eval("cardSelected" + currentCardRow);
This is how my problem is fixed.

Categories