This question already has answers here:
When is the comma operator useful?
(15 answers)
Closed 5 years ago.
I saw a comparison like the following in a question on SO:
(pNum != ('2','3','4','5','6','7','8','9'))
The OP has been trying to check if a number falls in a certain range but this code is inaccurate as it will always compare with right most value inside the brace(i.e. 9)
This means when pNum = 2 the comparison will return true and not false as was expected by OP who was expecting it to work like inArray or in.
My question is whether this sort of comparison is going to be useful in any real case in any scenario?
My question is whether this sort of comparison is going to be useful in any real case in any scenario?
No. As you observe, the comparison only compares the last item inside the bracket. So all it can accomplish is to confuse the reader.
If you intend to compare a variable with a set of values, you could use array#includes or array#indexOf >= 0. Something like:
console.log(['2','3','4','5','6','7','8','9'].includes('2'));
console.log(['2','3','4','5','6','7','8','9'].includes('6'));
console.log(['2','3','4','5','6','7','8','9'].includes('9'));
// IE
console.log(['2','3','4','5','6','7','8','9'].indexOf('2') >= 0);
console.log(['2','3','4','5','6','7','8','9'].indexOf('6') >= 0);
console.log(['2','3','4','5','6','7','8','9'].indexOf('9') >= 0);
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.
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?
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)) {
This question already has answers here:
Check variable equality against a list of values
(16 answers)
Closed 5 years ago.
This one is probably fairly straightforward, but I haven't succeeded in finding an answer as of yet. Anyway, what I want to do is compare one value against a group of others, and run the script if it matches one of them. Here's the verbose version of I want to do, which works fine, but I'm assuming there's a smarter, less verbose way to achieve this?
function updatePosition(e) {
if((e.target.innerHTML == 1) || (e.target.innerHTML == 4) ||
(e.target.innerHTML == 7)) {
console.log(e.target.innerHTML)
}
}
You can store all the valid comparison inside an array. Then you can use Array#Find() to get a matching value. If there is no matching value, you will get undefined
function updatePosition(num) {
let validNumbers = [1,4,7];
console.log(validNumbers.find(valid => valid === num));
}
updatePosition(4);
updatePosition(9);
This question already has answers here:
+ operator before expression in javascript: what does it do?
(4 answers)
Closed 10 years ago.
Reading through the source code of underscore.js I stumbled upon the following line:
... if (obj.length === +obj.length) { ...
That's a bit confusing for me. What is actually being compared here? I believe it has something to do about detecting native arrays, but cannot figure out what's actually going on. What does the + do? Why use === instead of ==? And what are the performance benefits of this style?
The + coerces the value to an Number (much like !! coerces it to a boolean).
if (x === +x)
...can be used to confirm that x itself contains an integer value. In this case it may be to make sure that the length property of obj is an integer and has not been overwritten by a string value, as that can screw up iteration if obj is treated as an array.
It is a silly (IMO) way of checking if obj.length is a Number. This is better:
typeof obj.length == "number"
The + coheres what is on the right side to be a number.
In this case if length was not a property on the object undefined would be returned. + undefined will yield Nan and this evalutation be false.
If the string can be coheres-ed into a number then it will be.. e.g + '1' will yield 1 as a Number this is especially important when dealing with hex values in string form e.g. +'0x7070' yields 28784