This question already has answers here:
Check variable equality against a list of values
(16 answers)
JavaScript: Simple way to check if variable is equal to one of two or more values? [duplicate]
(8 answers)
Closed 2 years ago.
I want to make my condition easier to read and wandering if it is possible to simplify this Scenario:
if((x === y)||(x === z)){...}
//and this one:
x = (x === y) || (x === z)? ... : ...;
//To something like:
if(x === (y || z)){...}
x = x === (y || z) ? ... : ...;
This would get rid of the tons of brackets and variable duplication as well as "sounding" logical (at least for me):
if this var x is this or that then I do this.
Especially when x is some long object reference e.g.:
this.someObject.KeyOfKeys[200].language === this.someOtherObject.KeyY.languages[10] || ...;
Or how do you deal with logical "easy" but cumbersome to write conditions?
You can use includes() like so:
if ([y, z].includes(x)) { ... }
x = [y, z].includes(x) ? ... : ...;
As noted in the comments, this will not work with IE11 and older browsers.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
To clarify:
This is purely for experimental purposes, to learn the quirks, odds and ends of a new (to me) language. I would of course write it readable if I ever were to share this code with anyone else. :-)
I have a function someFunction(x), and two global variables:
let m = 2;
let e = 5;
Inside the function, I want to check if x == m. If this is true, I'd like to pass m to a side function call (sideFunction(m)), then reassign x to e to complete someFunction.
This does work as expected:
const someFunction = x => {
if (x == m) {
sideFunction(m);
x = e;
}
doOtherStuffWith(x);
}
However, I'd like to shorten it, preferably to one line. This is also to understand more about ternaries and/or boolean chaining.
I have tried these two methods:
// Boolean chaining
const someFunction = x => {
x == m && sideFunction(m) && (function () {x = e})();
doOtherStuffWith(x);
}
This does not work, presumably because the assignment x = e only applies to the x in the local scope of the inner, anonymous function...?
// Ternary operator
const someFunction = x => {
x = (x == m && sideFunction(m)) ? e : x;
doOtherStuffWith(x);
}
This does not work, presumably because sideFunction(m) doesn't actually get called, for some reason...?
How can I fix these to make them work?
Alternatively, are there other, elegant ways to perform this check/call/reassignment without a full multi-line if block?
Thank you very much!
The problem with
x == m && sideFunction(m) && (function () {x = e})();
is that && evaluates left-to-right, and will stop as soon as the first falsey value is found. Unless sideFunction returns something explicitly truthy, the third IIFE:
(function () {x = e})()
will never run, resulting in x never being reassigned.
x is local in that function. If you can get the function to run, it will reassign x as desired.
You could use the comma operator:
x == m && (sideFunction(m), x = e);
Similarly
x = (x == m && sideFunction(m)) ? e : x;
won't work because sideFunction would have to return something truthy for the left side of the conditional to evaluate truthily - otherwise, x will be assigned to x, no change.
All this said - I'd highly recommend not doing any of these. Your first approach is much more readable, and readability is much more important than line conservation.
You could take a compound expression with a comma operator and do not care about the result value of sideFunction.
const fn = x => (x == m && (sideFunction(m), x = e), doOtherStuffWith(x));
The comma operator , can be used to chain expressions and return the last one e.g.,
var x = (1 + 2, 10 + 2, 100 + 2);
x;
//=> 102
We can use it to evaluate sideFunction(m) and return e: (sideFunction(m), e).
Since you always want to execute doOtherStuffWith you only need to work out whether to give it e or the original x:
const someFunction = x => doOtherStuffWith(x == m ? (sideFunction(m), e) : x);
This question already has answers here:
JavaScript `undefined` vs `void 0`
(4 answers)
Closed 7 years ago.
While doing some typescript I came over this thing I havent seen before in javascript.
constructor(public x: number = 0, public y: string = "none"){
this.color = "red";
}
that part is compiling into:
if (x === void 0) { x = 0; }
if (y === void 0) { y = "none"; }
But shouldn't it be typeof x === 'undefined'? if not, which one is better and why?
thanks
There are differences.
If you're checking for a global variable x,
then typeof x === 'undefined' will return true and x === void 0 throw a ReferenceError.
You would need to use window.x === void 0 to get true. However in this case it knows that x will at least be set to undefined because it is a function parameter, so that error will never be an issue.
I think for readability sake, I would prefer to use typeof x === 'undefined'.
Had some problems with a script running, which was mainly built around dropdown menus. Single equals = and exactly equals == were both used in the same function, though not same if statement. Could not see anything else amiss and made all uses ==, which seemed to resolve problem. I'm relatively new to Javascript, so was just wondering if combining different styles of equals makes a difference was all. Didn't think it did.
Your question doesn't really make sense - these are different operators. In javascript:
= is the assignment operator, e.g.
var x = 1;
if (x = 1) // This would not compare x to 1, it would assign the value 1 to x
// and then return the value to the if block which would decide
// whether the value is truthy or not (and in this case
// return true).
== is the comparison operator, e.g.
var x == 1; //This would not make sense (or run)
if (x == 1) {
=== does a comparison and ensures that both operands are the same type:
var x = "1";
if (x == 1) { //Returns true
if (x === 1) //returns false.
= assigns values to variables.
== and === are comparison operators.
Of course your script logic changes quite a bit when you exchange = and == operators.
This question already has answers here:
Shorthand for multiple OR expressions in if statement
(4 answers)
checking a variable value using an OR operator
(3 answers)
Closed 9 years ago.
i have this if statement and i wanna know if exist a better way to write it
if(i == "502" || i == "562" || i == "584" || i == "482" || i == "392"){
//Some Stuff here
}
That works fine. You can also use Array.indexOf
if(['502', '562', '584', '482', '392'].indexOf(i) !== -1)
{
/*Do Stuff*/
}
However, you should be careful with Array.indexOf because it is not supported by versions of Internet Explorer before IE9 :(. That is why $.inArray is often suggested over Array.indexOf.
Use $.inArray() method by jQuery:
var a = ['502', '562', '584', '482', '392'];
var i = '482';
if ($.inArray(i, a) > -1) {
alert(i);
}
References:
jQuery.inArray() - jQuery API Documentation
switch(i)
{
case 502:
case 562:
case 584:
case 482:
case 392: //do stuff
break;
}
While the other answers are very useful, they don't do exactly the same as your code. If you compare a string with only digits will compare equal (using ==) to a number it represents (and possibly other objects that have a toString() equal to that). But the same isn't true with indexOf, $.inArray or switch:
var i = 502;
i == "502"' // True
["502"].indexOf(i) // False
An exact equivalent of your code would be:
var VALUES = ['502', '562', '584', '482', '392'];
if(VALUES.some(function(e) { return e == i; }) {
// do something
}
Object lookups are pretty much as fast as variable lookups.
if ({
"502": 1,
"562": 1,
"584": 1,
"482": 1, // if you're concerned about conflict with `Object.prototype`
"392": 1 // then consider using `{...}[i] === 1` or
}[i]) { // `{...}.hasOwnProperty(i)`
// code if found
}
Be aware that this method won't let you make the distinction between i === 502 and i === '502' as all keys in Objects are Strings.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
javascript function inArray
In Python, I can do multi-equivalence testing by doing:
if x in [1, 2, 3, 4, 5]:
do something
How would I do this in javascript?. Currently I'm doing:
if (x == 1 || x == 2 || x == 3 || x == 4 || x == 5) {
do something
}
In JavaScript there is indexOf method:
if ([1,2,3,4,5].indexOf(x) > -1) {
// do something
}
Note, that this method is not supported by some old browsers, so it is recommended to use shim.
By the way, in operator exists in JavaScript, and is primarily used for checking property existence in objects, for example:
"id" in { id: 123 } === true;
"id" in { ib: 123 } === false;
You can use a switch if you only want to specify the x variable once:
switch (x) {
case 1:
case 2:
case 3:
case 4:
case 5:
// do something
}
If the values are really like in the example, you can just check the end values:
if (x >= 1 && x <= 5) {
// do something
}