Checking value with JavaScript [duplicate] - javascript

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.

Related

Usefulness of the comma operator in comparisons [duplicate]

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

What is the Javascript equivalent of writing 'If not" [duplicate]

This question already has answers here:
Best way to find if an item is in a JavaScript array? [duplicate]
(8 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
Python programmer here.
I don't know how to write this. I tried using 'if !in' and '!if in', but I don't know how. Tried to Google it but got no results.
The correct syntax is
if(!condition){
expression();
}
Note that you need parenthesis around the condition.
#plalx wants a formal definition, and here you go:
IfStatement:
if(Expression) Statement else Statement
if(Expression) Statement
In case of any ambiguity the else would be matched with the nearest if.
If you have some value:
var excludeMe = "something unwanted";
Then you can use the following if statement:
if(myTestCase !== excludeMe) { //do something...}
Keep in mind that != does not check type and !== does check type. So, 1 != "1" is false and 1 !== "1" is true.

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.

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