A better way to use IF statement with OR [duplicate] - javascript

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.

Related

Does this simple way of writing multiple conditions on an if exist? [duplicate]

This question already has answers here:
Check variable equality against a list of values
(16 answers)
Concise way to compare against multiple values [duplicate]
(8 answers)
Closed 7 years ago.
Whats the prettiest way to compare one value against multiples options?
I know there are loads of ways of doing this, but I'm looking for the neatest.
i ask because i'd hoped this was workable (it isn't, quite obviously when you look at it):
if (foobar == (foo||bar) ) {
//do something
}
Don't try to be too sneaky, especially when it needlessly affects performance.
If you really have a whole heap of comparisons to do, just format it nicely.
if (foobar === foo ||
foobar === bar ||
foobar === baz ||
foobar === pew) {
//do something
}
What i use to do, is put those multiple values in an array like
var options = [foo, bar];
and then, use indexOf()
if(options.indexOf(foobar) > -1){
//do something
}
for prettiness:
if([foo, bar].indexOf(foobar) +1){
//you can't get any more pretty than this :)
}
and for the older browsers:
( https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/IndexOf )
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:
if (foobar === foo || foobar === bar) {
//do something
}
And, if you have lots of values (perhaps hundreds or thousands), then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:
// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);
// test the Set at runtime
if (tSet.has(foobar)) {
// do something
}
For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.
You can use a switch:
switch (foobar) {
case foo:
case bar:
// do something
}
Just for kicks, since this Q&A does seem to be about syntax microanalysis, a tiny tiny modification of André Alçada Padez's suggestion(s):
(and of course accounting for the pre-IE9 shim/shiv/polyfill he's included)
if (~[foo, bar].indexOf(foobar)) {
// pretty
}
Why not using indexOf from array like bellow?
if ([foo, bar].indexOf(foobar) !== -1) {
// do something
}
Just plain Javascript, no frameworks or libraries but it will not work on IE < 9.
(foobar == foo || foobar == bar) otherwise if you are comparing expressions based only on a single integer, enumerated value, or String object you can use switch. See The switch Statement. You can also use the method suggested by André Alçada Padez. Ultimately what you select will need to depend on the details of what you are doing.
I like the pretty form of testing indexOf with an array, but be aware, this doesn't work in all browsers (because Array.prototype.indexOf is not present in old IExplorers).
However, there is a similar way by using jQuery with the $.inArray() function :
if ($.inArray(field, ['value1', 'value2', 'value3']) > -1) {
alert('value ' + field + ' is into the list');
}
It could be better, so you should not test if indexOf exists.
Be careful with the comparison (don't use == true/false), because $.inArray returns the index of matching position where the value has been found, and if the index is 0, it would be false when it really exist into the array.

Do While Loop exits despite condition being met [duplicate]

This question already has answers here:
Check variable equality against a list of values
(16 answers)
Concise way to compare against multiple values [duplicate]
(8 answers)
Closed 7 years ago.
Whats the prettiest way to compare one value against multiples options?
I know there are loads of ways of doing this, but I'm looking for the neatest.
i ask because i'd hoped this was workable (it isn't, quite obviously when you look at it):
if (foobar == (foo||bar) ) {
//do something
}
Don't try to be too sneaky, especially when it needlessly affects performance.
If you really have a whole heap of comparisons to do, just format it nicely.
if (foobar === foo ||
foobar === bar ||
foobar === baz ||
foobar === pew) {
//do something
}
What i use to do, is put those multiple values in an array like
var options = [foo, bar];
and then, use indexOf()
if(options.indexOf(foobar) > -1){
//do something
}
for prettiness:
if([foo, bar].indexOf(foobar) +1){
//you can't get any more pretty than this :)
}
and for the older browsers:
( https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/IndexOf )
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:
if (foobar === foo || foobar === bar) {
//do something
}
And, if you have lots of values (perhaps hundreds or thousands), then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:
// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);
// test the Set at runtime
if (tSet.has(foobar)) {
// do something
}
For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.
You can use a switch:
switch (foobar) {
case foo:
case bar:
// do something
}
Just for kicks, since this Q&A does seem to be about syntax microanalysis, a tiny tiny modification of André Alçada Padez's suggestion(s):
(and of course accounting for the pre-IE9 shim/shiv/polyfill he's included)
if (~[foo, bar].indexOf(foobar)) {
// pretty
}
Why not using indexOf from array like bellow?
if ([foo, bar].indexOf(foobar) !== -1) {
// do something
}
Just plain Javascript, no frameworks or libraries but it will not work on IE < 9.
(foobar == foo || foobar == bar) otherwise if you are comparing expressions based only on a single integer, enumerated value, or String object you can use switch. See The switch Statement. You can also use the method suggested by André Alçada Padez. Ultimately what you select will need to depend on the details of what you are doing.
I like the pretty form of testing indexOf with an array, but be aware, this doesn't work in all browsers (because Array.prototype.indexOf is not present in old IExplorers).
However, there is a similar way by using jQuery with the $.inArray() function :
if ($.inArray(field, ['value1', 'value2', 'value3']) > -1) {
alert('value ' + field + ' is into the list');
}
It could be better, so you should not test if indexOf exists.
Be careful with the comparison (don't use == true/false), because $.inArray returns the index of matching position where the value has been found, and if the index is 0, it would be false when it really exist into the array.

How to generate different spawn points for objects (Javascript)? [duplicate]

This question already has answers here:
Check variable equality against a list of values
(16 answers)
Concise way to compare against multiple values [duplicate]
(8 answers)
Closed 7 years ago.
Whats the prettiest way to compare one value against multiples options?
I know there are loads of ways of doing this, but I'm looking for the neatest.
i ask because i'd hoped this was workable (it isn't, quite obviously when you look at it):
if (foobar == (foo||bar) ) {
//do something
}
Don't try to be too sneaky, especially when it needlessly affects performance.
If you really have a whole heap of comparisons to do, just format it nicely.
if (foobar === foo ||
foobar === bar ||
foobar === baz ||
foobar === pew) {
//do something
}
What i use to do, is put those multiple values in an array like
var options = [foo, bar];
and then, use indexOf()
if(options.indexOf(foobar) > -1){
//do something
}
for prettiness:
if([foo, bar].indexOf(foobar) +1){
//you can't get any more pretty than this :)
}
and for the older browsers:
( https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/IndexOf )
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:
if (foobar === foo || foobar === bar) {
//do something
}
And, if you have lots of values (perhaps hundreds or thousands), then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:
// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);
// test the Set at runtime
if (tSet.has(foobar)) {
// do something
}
For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.
You can use a switch:
switch (foobar) {
case foo:
case bar:
// do something
}
Just for kicks, since this Q&A does seem to be about syntax microanalysis, a tiny tiny modification of André Alçada Padez's suggestion(s):
(and of course accounting for the pre-IE9 shim/shiv/polyfill he's included)
if (~[foo, bar].indexOf(foobar)) {
// pretty
}
Why not using indexOf from array like bellow?
if ([foo, bar].indexOf(foobar) !== -1) {
// do something
}
Just plain Javascript, no frameworks or libraries but it will not work on IE < 9.
(foobar == foo || foobar == bar) otherwise if you are comparing expressions based only on a single integer, enumerated value, or String object you can use switch. See The switch Statement. You can also use the method suggested by André Alçada Padez. Ultimately what you select will need to depend on the details of what you are doing.
I like the pretty form of testing indexOf with an array, but be aware, this doesn't work in all browsers (because Array.prototype.indexOf is not present in old IExplorers).
However, there is a similar way by using jQuery with the $.inArray() function :
if ($.inArray(field, ['value1', 'value2', 'value3']) > -1) {
alert('value ' + field + ' is into the list');
}
It could be better, so you should not test if indexOf exists.
Be careful with the comparison (don't use == true/false), because $.inArray returns the index of matching position where the value has been found, and if the index is 0, it would be false when it really exist into the array.

Why can't I reassign this variable inside an if statement using Javascript? [duplicate]

This question already has answers here:
What is the difference between ( for... in ) and ( for... of ) statements?
(18 answers)
Closed 1 year ago.
I am experiencing some weird behaviour that I think is scope related, but I can't explain why it's happening.
So this is the problematic piece of code. I'm trying to Camel Case some words and differentiate between text separated by dashes and underscores. Ignore the fact that the algorithm isn't completely correct yet, that's not the point. This is the stage I noticed the problem.
function toCamelCase(str){
let isDash = false
for (let char in str) {
if (char === "-") {
isDash = true
}
}
if (isDash) {
return str.split("-").map(word => word[0].toUpperCase() + word.slice(1, word.length + 1)).join("")
} else {
return str.split("_").map(word => word[0].toUpperCase() + word.slice(1, word.length + 1)).join("")
}
}
let result = "why-false"
console.log(toCamelCase(result))
So isDash determines which type of separator does the text contain. I can obviously use an arrow function instead of this approach, and it would work perfectly. Something like this:
let isDash = () => {
for (let char in str) {
if (char === "-") {
return true
}
But I can't understand why doesn't the previous example work as well. I've read about scope and it should be possible to reassign to that variable if it was defined at a higher level. Even if I defined isDash outside the function, it still didn't work. It's value always remains the initial one: false. Why isn't the if statement changing its value to true?
let x = [1, 4, 5, 7]
let txt = 0
let working = "no"
for (let i in x) {
txt += x[i]
if (txt > 4) {
working = "yes"
}
}
console.log(working)
As you can see, if I write something similar to demonstrate if it's possible to use the variable in a nested if statement, it works fine and working will log yes. What am I missing here? I would really appreciate some help, this really is a dead end to me and I wouldn't have asked for help if I could've figured it out myself. Big thanks to anyone that can explain this stuff to me!
The issue here is your for loop:
for (let char in str) {
if (char === "-") {
isDash = true
}
}
The for-in loop loops over indices or keys, not values (you can test this by doing console.log(char); in the loop). Instead, use a for-of loop.
The issue is that you're using the for...in statement, which loops over enumerable property names of an object.
for (let char in str) {
if (char === "-") {
isDash = true
}
}
You can use for...of statement to iterate over Strings and use const if you are not going to reassign the variable inside the block.
This way:
for (const char of str) {
if (char === "-") {
isDash = true
}
}
I'm fairly certain the reason for this is your use of 'let' instead of 'var'. (To be honest I hadn't seen it used before this post...).
See this article:
https://www.google.com/amp/s/www.geeksforgeeks.org/difference-between-var-and-let-in-javascript/amp/
And if this fixes your issue, have a read up further on the difference s between the two.
I personally would always just use var .

Is it possible to create an if statement in this sort of way? [duplicate]

This question already has answers here:
Check variable equality against a list of values
(16 answers)
Concise way to compare against multiple values [duplicate]
(8 answers)
Closed 7 years ago.
Whats the prettiest way to compare one value against multiples options?
I know there are loads of ways of doing this, but I'm looking for the neatest.
i ask because i'd hoped this was workable (it isn't, quite obviously when you look at it):
if (foobar == (foo||bar) ) {
//do something
}
Don't try to be too sneaky, especially when it needlessly affects performance.
If you really have a whole heap of comparisons to do, just format it nicely.
if (foobar === foo ||
foobar === bar ||
foobar === baz ||
foobar === pew) {
//do something
}
What i use to do, is put those multiple values in an array like
var options = [foo, bar];
and then, use indexOf()
if(options.indexOf(foobar) > -1){
//do something
}
for prettiness:
if([foo, bar].indexOf(foobar) +1){
//you can't get any more pretty than this :)
}
and for the older browsers:
( https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/IndexOf )
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:
if (foobar === foo || foobar === bar) {
//do something
}
And, if you have lots of values (perhaps hundreds or thousands), then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:
// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);
// test the Set at runtime
if (tSet.has(foobar)) {
// do something
}
For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.
You can use a switch:
switch (foobar) {
case foo:
case bar:
// do something
}
Just for kicks, since this Q&A does seem to be about syntax microanalysis, a tiny tiny modification of André Alçada Padez's suggestion(s):
(and of course accounting for the pre-IE9 shim/shiv/polyfill he's included)
if (~[foo, bar].indexOf(foobar)) {
// pretty
}
Why not using indexOf from array like bellow?
if ([foo, bar].indexOf(foobar) !== -1) {
// do something
}
Just plain Javascript, no frameworks or libraries but it will not work on IE < 9.
(foobar == foo || foobar == bar) otherwise if you are comparing expressions based only on a single integer, enumerated value, or String object you can use switch. See The switch Statement. You can also use the method suggested by André Alçada Padez. Ultimately what you select will need to depend on the details of what you are doing.
I like the pretty form of testing indexOf with an array, but be aware, this doesn't work in all browsers (because Array.prototype.indexOf is not present in old IExplorers).
However, there is a similar way by using jQuery with the $.inArray() function :
if ($.inArray(field, ['value1', 'value2', 'value3']) > -1) {
alert('value ' + field + ' is into the list');
}
It could be better, so you should not test if indexOf exists.
Be careful with the comparison (don't use == true/false), because $.inArray returns the index of matching position where the value has been found, and if the index is 0, it would be false when it really exist into the array.

Categories

Resources