Shorthand IF Statement - javascript

I'm curious, is there a simpler way to say
if(myVar == myVal || myVar == myOtherVal){ /*...*/ }
such as:
if(myVar == myVal || myOtherVal){ /* */ }
I am aware that my proposed code only checkes to see whether myVar equals myVal or myOtherVal is not null (undefined) and false.
So, as I stated before, is there a simpler way to write
if(myVar == myVal || myVar == myOtherVal){ /*...*/ }
Just curious to know if there's some sort of jS shorthand if statment that works like this that I have missed.
Thanks in advance.

This should be what you are looking for. http://snook.ca/archives/javascript/testing_for_a_v

You could use arrays:
if([myVal, myOtherVal].indexOf(myVar) + 1) { /* or > -1 or !== -1 */ }
Or switch statements:
switch(myVar) {
case myVal:
case myOtherVal:
/* */
break;
}
These only really apply when comparing the variable to more than two possible values, though.

Not that I know of.
You could use the Array's indexOf with an array if you really wanted.

Another way is to use && as a "guard":
(myVar == myVal || myVar == myOtherVal) && /* expression */
But I don't recommend it. Your code should be easily read and maintained, so:
if (myVar == myVal || myVar == myOtherVal) {
/* do stuff */
}
is much better to me.

Ternary Operator:
result = ((myVar==myval)||(myVar==myOtherVal)) ? x : y;
Can be:
if((myVar==myVal) || (myVar==myOtherVal))
result = x;
else
result = y;
Also:
((myVar==myval)||(myVar==myOtherVal)) ? someFunction() : otherFunction();
Is the same as:
if((myVar==myVal) || (myVar==myOtherVal))
someFunction();
else
otherFunction();

Related

Why won't my JavaScript account system code work or run? [duplicate]

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
Is there an easier way to determine if a variable is equal to a range of values, such as:
if x === 5 || 6
rather than something obtuse like:
if x === 5 || x === 6
?
You can stash your values inside an array and check whether the variable exists in the array by using [].indexOf:
if([5, 6].indexOf(x) > -1) {
// ...
}
If -1 is returned then the variable doesn't exist in the array.
Depends on what sort of test you're performing. If you've got static strings, this is very easy to check via regular expressions:
if (/^[56ab]$/.test(item)) {
//-or-
if (/^(foo|bar|baz|fizz|buzz)$/.test(item)) {
doStuff();
} else {
doOtherStuff();
}
If you've got a small set of values (string or number), you can use a switch:
switch (item) {
case 1:
case 2:
case 3:
doStuff();
break;
default:
doOtherStuff();
break;
}
If you've got a long list of values, you should probably use an array with ~arr.indexOf(item), or arr.contains(item):
vals = [1,3,18,3902,...];
if (~vals.indexOf(item)) {
doStuff();
} else {
doOtherStuff();
}
Unfortunately Array.prototype.indexOf isn't supported in some browsers. Fortunately a polyfill is available. If you're going through the trouble of polyfilling Array.prototype.indexOf, you might as well add Array.prototype.contains.
Depending on how you're associating data, you could store a dynamic list of strings within an object as a map to other relevant information:
var map = {
foo: bar,
fizz: buzz
}
if (item in map) {
//-or-
if (map.hasOwnProperty(item)) {
doStuff(map[item]);
} else {
doOtherStuff();
}
in will check the entire prototype chain while Object.prototype.hasOwnProperty will only check the object, so be aware that they are different.
It's perfectly fine. If you have a longer list of values, perhaps you can use the following instead:
if ([5,6,7,8].indexOf(x) > -1) {
}
Yes. You can use your own function. This example uses .some:
var foo = [ 5, 6 ].some(function(val) {
return val === x;
});
foo; // true
This is what I've decided to use:
Object.prototype.isin = function() {
for(var i = arguments.length; i--;) {
var a = arguments[i];
if(a.constructor === Array) {
for(var j = a.length; j--;)
if(a[j] == this) return true;
}
else if(a == this) return true;
}
return false;
}
You would use it like this:
var fav = 'pear',
fruit = ['apple', 'banana', 'orange', 'pear'],
plu = [4152, 4231, 3030, 4409];
if (fav.isin(fruit, plu, 'eggs', 'cheese')) {
//do something cool
}
The advantages are:
it works in IE < 9;
it reads naturally from left to right;
you can feed it arrays or separate values.
If you don't want to allow type coercion (indexOf does not), change the two == to ===. As it stands:
fav = "4231";
plu.indexOf(fav) //-1
fav.isin(plu) //true
no, there might be a few tricks that are case specific but in general i write code like this:
if (someVariable === 1 ||
someVariable === 2 ||
someVariable === 7 ||
someVariable === 12 ||
someVariable === 14 ||
someVariable === 19) {
doStuff();
moreStuff();
} else {
differentStuff();
}
The simple answer is no. You can use a switch statement, which is easier to read if you are comparing a lot of string values, but using it for two values wouldn't look any better.
[Edit] this seems to work, but as Dan pointed out, it is actually a false positive. Do not use this method. I leave it here for educational purposes.
Easiest way I know :
a = [1,2,3,4,5];
if(3 in a) alert("true"); // will alert true
Tested in Chrome console. Not sure if it works in other browsers.

If keydown !== A,B or C in Javascript? [duplicate]

I want to write an if/else statement that tests if the value of a text input does NOT equal either one of two different values. Like this (excuse my pseudo-English code):
var test = $("#test").val();
if (test does not equal A or B){
do stuff;
}
else {
do other stuff;
}
How do I write the condition for the if statement on line 2?
Think of ! (negation operator) as "not", || (boolean-or operator) as "or" and && (boolean-and operator) as "and". See Operators and Operator Precedence.
Thus:
if(!(a || b)) {
// means neither a nor b
}
However, using De Morgan's Law, it could be written as:
if(!a && !b) {
// is not a and is not b
}
a and b above can be any expression (such as test == 'B' or whatever it needs to be).
Once again, if test == 'A' and test == 'B', are the expressions, note the expansion of the 1st form:
// if(!(a || b))
if(!((test == 'A') || (test == 'B')))
// or more simply, removing the inner parenthesis as
// || and && have a lower precedence than comparison and negation operators
if(!(test == 'A' || test == 'B'))
// and using DeMorgan's, we can turn this into
// this is the same as substituting into if(!a && !b)
if(!(test == 'A') && !(test == 'B'))
// and this can be simplified as !(x == y) is the same as (x != y)
if(test != 'A' && test != 'B')
ECMA2016 answer, especially good when checking against multiple values:
if (!["A","B", ...].includes(test)) {}
In general it would be something like this:
if(test != "A" && test != "B")
You should probably read up on JavaScript logical operators.
I do that using jQuery
if ( 0 > $.inArray( test, [a,b] ) ) { ... }
For a larger number of values that is checked against often, it may be more efficient to check if the value does not exist in a Set.
const values = new Set(["a", "b"]);
if(!values.has(someValue)){
// do something
} else {
// do something else
}
var test = $("#test").val();
if (test != 'A' && test != 'B'){
do stuff;
}
else {
do other stuff;
}
You used the word "or" in your pseudo code, but based on your first sentence, I think you mean and. There was some confusion about this because that is not how people usually speak.
You want:
var test = $("#test").val();
if (test !== 'A' && test !== 'B'){
do stuff;
}
else {
do other stuff;
}
This can be done with a switch statement as well. The order of the conditional is reversed but this really doesn't make a difference (and it's slightly simpler anyways).
switch(test) {
case A:
case B:
do other stuff;
break;
default:
do stuff;
}

Javascript Value Comparison Explanation

What is the difference between these two conditional statements in Javascript?
function comparisonTest() {
var value = "A value";
var compare1 = 5;
var compare2 = "String";
var compare3 = false;
if (value == compare1 || value == compare2 || value == compare3) console.write("True");
else console.write("False");
}
This works as it should - it returns false because the values don't match. However, when I change the conditional to the following...
function comparisonTest() {
var value = "A value";
var compare1 = 5;
var compare2 = "String";
var compare3 = false;
if (value == compare1 || compare2 || compare3) console.write("True");
else console.write("False");
}
it always returns True. I thought that maybe there would be a shorter way of writing that condition for multiple comparisons (although a loop would function just fine), but this is clearly not a way to approach this.
What is going on behind-the-scenes or, rather, how is it being interpreted so that in the second case it always returns true? None of the values I declared are 1 or true, so that's definitely not the problem.
That's because this:
if (value == compare1 || compare2 || compare3)
is the same as this:
if ((value == compare1) || compare2 || compare3)
And, you will see that compare2is a truthy value which satisfies the || operator. See this MDN article on operator precedence for why the == gets evaluated first which makes your first code block work, but makes your second one evaluate like I've shown.
If you want to compare all of them to value, you have to write it out the longhand way like you did in your first code block where you compare each one separately to value.
You may also want to look into using === more often so then you don't have to worry about possible type conversions making things equal that you never intended to be equal. I have a guideline in my own coding to always used === and !== unless there's an explicit reason to want a type conversion. I believe this saves some accidental bugs. See here for more info.
Here is another option:
function comparisonTest() {
var value = "A value";
var answers = [5, "String", false];
/* IE may requires shim found here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
*/
if (answers.indexOf(value) === -1) {
// False
} else {
// True
}
}
Unfortunately I do not believe there is a short way to write conditionals in JavaScript.
The reason the second example returns true is because when you evaluate compare2 this is a truthy value in JavaScript.
I recommend this post about truthy and falsey values in JavaScript
As an aside you may want to look into the difference between == and === in JavaScript

JS: check existence of a var that equals 0

I have a piece of code that tests for the existence of a variable, using an if statement like the example below. I need to do one thing if the var is set, a different thing if its not. In a certain test case, the var needed to be set to 0, but that is the same is having an unset var in JS, apparently:
var toMatch;
toMatch = 0;
if (!toMatch) {
document.write("no");
} else {
document.write(toMatch);
}
// html is "no"
jsFiddle
So my problem is, how do I test for a var if its value is legitimately zero. I should point out, that in my function possible values to be passed are 0-40+.
In the past I've used a work around like setting the initial value to a number high enough that it is not likely to be passed to the function but that seems hackey to me. Is there a better way to do it?
var toMatch;
toMatch = 0;
if (toMatch === 0) { // or !== if you're checking for not zero
document.write("no");
} else {
document.write(toMatch);
}
toMatch === 0 will check for zero.
toMatch === undefined will check for undefined
the triple equals are strict comparison operators for this sort of scenario. See this blessed question: Difference between == and === in JavaScript
Instead of
if (toMatch)
use
if (toMatch == null)
You can see if a name is undefined with:
if (typeof bad_name === "undefined") {
Javascript is a bit funny when it comes to values and boolean checks. I suggest reading about Truthy and Falsey in Javascript.
You should use the identity inequality operator !==:
var toMatch;
toMatch = 0;
if (toMatch !== 0) {
document.write("no");
} else {
document.write(toMatch);
}
It is also worth understanding the differences between == and ===.

is there something like isset of php in javascript/jQuery? [duplicate]

This question already has answers here:
JavaScript isset() equivalent
(28 answers)
Closed 6 years ago.
Is there something in javascript/jQuery to check whether variable is set/available or not? In php, we use isset($variable) to check something like this.
thanks.
Try this expression:
typeof(variable) != "undefined" && variable !== null
This will be true if the variable is defined and not null, which is the equivalent of how PHP's isset works.
You can use it like this:
if(typeof(variable) != "undefined" && variable !== null) {
bla();
}
JavaScript isset() on PHP JS
function isset () {
// discuss at: http://phpjs.org/functions/isset
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: FremyCompany
// + improved by: Onno Marsman
// + improved by: Rafał Kukawski
// * example 1: isset( undefined, true);
// * returns 1: false
// * example 2: isset( 'Kevin van Zonneveld' );
// * returns 2: true
var a = arguments,
l = a.length,
i = 0,
undef;
if (l === 0) {
throw new Error('Empty isset');
}
while (i !== l) {
if (a[i] === undef || a[i] === null) {
return false;
}
i++;
}
return true;
}
typeof will serve the purpose I think
if(typeof foo != "undefined"){}
If you want to check if a property exists: hasOwnProperty is the way to go
And since most objects are properties of some other object (eventually leading to the window object) this can work well for checking if values have been declared.
Some parts of each of these answers work. I compiled them all down into a function "isset" just like the question was asking and works like it does in PHP.
// isset helper function
var isset = function(variable){
return typeof(variable) !== "undefined" && variable !== null && variable !== '';
}
Here is a usage example of how to use it:
var example = 'this is an example';
if(isset(example)){
console.log('the example variable has a value set');
}
It depends on the situation you need it for but let me break down what each part does:
typeof(variable) !== "undefined" checks if the variable is defined at all
variable !== null checks if the variable is null (some people explicitly set null and don't think if it is set to null that that is correct, in that case, remove this part)
variable !== '' checks if the variable is set to an empty string, you can remove this if an empty string counts as set for your use case
Hope this helps someone :)
Not naturally, no... However, a googling of the thing gave this: http://phpjs.org/functions/isset:454
http://phpjs.org/functions/isset:454
phpjs project is a trusted source. Lots of js equivalent php functions available there. I have been using since a long time and found no issues so far.
The problem is that passing an undefined variable to a function causes an error.
This means you have to run typeof before passing it as an argument.
The cleanest way I found to do this is like so:
function isset(v){
if(v === 'undefined'){
return false;
}
return true;
}
Usage:
if(isset(typeof(varname))){
alert('is set');
} else {
alert('not set');
}
Now the code is much more compact and readable.
This will still give an error if you try to call a variable from a non instantiated variable like:
isset(typeof(undefVar.subkey))
thus before trying to run this you need to make sure the object is defined:
undefVar = isset(typeof(undefVar))?undefVar:{};
Here :)
function isSet(iVal){
return (iVal!=="" && iVal!=null && iVal!==undefined && typeof(iVal) != "undefined") ? 1 : 0;
} // Returns 1 if set, 0 false
in addition to #emil-vikström's answer, checking for variable!=null would be true for variable!==null as well as for variable!==undefined (or typeof(variable)!="undefined").
You can just:
if(variable||variable===0){
//Yes it is set
//do something
}
else {
//No it is not set
//Or its null
//do something else
}

Categories