Javascript multiple or condition check - javascript

I have struck with some simple if else checking
var IsCompanyContacttitleUpdate = false;
var ContactStatus = -1;
if ((IsCompanyContacttitleUpdate == false) && (ContactStatus == 2 || 3 || 4))
{
alert('inside if');
}
else if (IsCompanyContacttitleUpdate == false && ContactStatus == 2) {
alert('inside else if');
}
else {
alert('yup yup else');
}
In this case i expected to execute the else part. but its not fired. Please help me to solve this one... Thanks in advance
please see the fiddle
http://jsfiddle.net/vuHYn/1/

This ContactStatus == 2 || 3 || 4 is invalid (maybe invalid is not the correct word, to be more accurate let's say that it's not doing what you think it does)
For your scenario you'll need to use
ContactStatus == 2 || ContactStatus == 3 || ContactStatus == 4
Your code could be tranlated to
ContactStatus == 2 || true || true
And this is always true.

the problem is (ContactStatus == 2 || 3 || 4)
the correct way should (ContactStatus == 2 || ContactStatus == 3 || ContactStatus == 4)

(ContactStatus == 2 || 3 || 4))
Here is your problem. You are saying if ContactStatus equals 2, it is true, OR true OR true.
False = 0, True is anything not 0.
You need to rewrite that as:
(ContactStatus == 2 || ContactStatus == 3 || ContactStatus == 4))
It should work if you change that one thing

Would this work? I changed the if condition from (ContactStatus == 2 || 3 || 4) to ((ContactStatus == 2) || (ContactStatus == 3) || (ContactStatus == 4)).
(ContactStatus == 2 || 3 || 4) evaluates (ContactStatus == 2); since it's true, it evaluates 3 as a condition. Since 3 is different from 0 (zero), then is results as true; and the whole OR evaluates to true. The final result is that the whole if condition is true and the "then" branch is selected.
var IsCompanyContacttitleUpdate = false;
var ContactStatus = 6;
if ((IsCompanyContacttitleUpdate == false) && ((ContactStatus == 2) || (ContactStatus == 3) || (ContactStatus == 4)))
{
alert('inside if')
} else if (IsCompanyContacttitleUpdate == false && ContactStatus == 2) {
alert('inside else if')
} else {
alert('yup yup else');
}

Related

connect 3 different true statements to an IF ELSE

I want return true if the number is an integer with 4 or 6 digits. no decimals or letter allowed
The thing is not working is the if its really a number check and if its got a decimal.
i think i got already the right functions applied to it but i just cant connect them properly to my if statement.
so i want to check if 3 different things a true then return true but didnt figured out
Please if possible only answer with a hint or a link or SUDO Code or stuff i can look up.
gonna answer the question myself when i figured it out
JS
function validatePIN (pin) {
//return true or false
var result = (pin - Math.floor(pin)) !== 0;
if( pin.length === 4 || isNaN(pin) || result) {
return true
} else if ( pin.length === 6 || isNaN(pin) || result) {
return true
} else return false
}
Thanks
A simple regular expression can be used to test that is is 4 or 6 numbers.
function isValidPin (pin) {
return /^(\d{4}|\d{6})$/.test(pin.toString());
}
console.log(isValidPin(123));
console.log(isValidPin("1234"));
console.log(isValidPin("12345"));
console.log(isValidPin("123456"));
console.log(isValidPin("1234567"));
console.log(isValidPin("12.45"));
console.log(isValidPin("12e45"));
You can check the conditions with the AND operator (&&).
function validatePIN (pin) {
//return true or false
var result = (pin - Math.floor(pin)) !== 0;
if( pin.length === 4 && isNaN(pin) && result)
{ return true} else if ( pin.length === 6 && isNaN(pin) && result) {
return true
} else return false
}
You need to change your or to and
function validatePIN (pin) {
//return true or false
var result = (pin - Math.floor(pin)) !== 0;
if( pin.length === 4 && isNaN(pin) && result)
{ return true}
else if ( pin.length === 6 && isNaN(pin) && result) {
return true
} else return false
}
Ty this:
function validatePIN(pin) {
var parsed = Math.parseInt(pin, 10);
// if it's not an integer
if(pin !== parsed.toString()) return false;
return pin.length === 4 || pin.length === 6;
}
perhaps I'm mistaken - but you could just check if the length is 4 OR 6, and continue your other two checks:
function validatePIN (pin) {
//return true or false
var result = (pin - Math.floor(pin)) !== 0;
if(!isNaN(pin) && (pin.length === 4 || pin.length === 6) && result) {
return true
} else return false
}
I've also edited your code, as it seemed illogical returning true for NaN.
I think you want this. You should use regular expression for simplicity.
console.log(445584, validatePin(445584));
console.log("445584", validatePin("445584"));
console.log("alj454", validatePin("alj454"));
console.log(4455.84, validatePin(4455.84));
function validatePin(pin){
return /^(\d{4}|\d{6})$/.test(pin);
}
You might want to look into using isNaN() to detect if there are any characters that aren't numbers.
Also, using .toString() so you can check the .length.

This code isn't working & is their a more efficient way to do this rather than using a else if statement?

I'm new to all this, i have a project for college, can't seem to get this to work and it seems to have a lot of repeating code, any help would be great, thanks.
var strength = document.getElementById('getstren');
strength.innerHTML = Math.floor((Math.random() * 17) + 1);
if (strength == 1) {
document.getElementById('ath').innerHTML = "-5"
}else if (strength == 2 || strength == 3) {
document.getElementById('ath').innerHTML = "-4"
}else if (strength == 4 || strength == 5) {
document.getElementById('ath').innerHTML = "-3"
}else if (strength == 6 || strength == 7) {
document.getElementById('ath').innerHTML = "-2"
}
else if (strength == 8 || strength == 9) {
document.getElementById('ath').innerHTML = "-1"
}
else if (strength == 10 || strength == 11) {
document.getElementById('ath').innerHTML = "0"
}
else if (strength == 12 || strength == 13) {
document.getElementById('ath').innerHTML = "1"
}
else if (strength == 14 || strength == 15) {
document.getElementById('ath').innerHTML = "2"
}
else if (strength == 16 || strength == 17) {
document.getElementById('ath').innerHTML = "3"
}
else if (strength == 18) {
document.getElementById('ath').innerHTML = "4"
}
I think it should display a figure for strength and should display another figure for athletics depending on the first figure!
Firstly, you need to access the innerHTML of strength and use parseInt to make it an integer. Secondly, you can use the following statement to make your code simpler: document.getElementById('ath').innerHTML = Math.floor(strength / 2) - 5.
var strength = document.getElementById('getstren');
strength.innerHTML = Math.floor((Math.random() * 17) + 1);
document.getElementById('ath').innerHTML = Math.floor(parseInt(strength) / 2) - 5;
The variable strength is a HTMLElement. Therefore, it will never be equal to an integer.
To access the html of the HTMLElement, you can use the innerHTML property which returns a string. You can use parseInt to cast it to an integer.
Example:
// Assumes strength is defined
const strengthInt = parseInt(strength.innerHTML)
if(strength == 1){
// Set ath html
}
//Other if-else here
As for an alternative to if-else, look at switch.

Regex in javascript global catch failed [duplicate]

This question already has answers here:
regex has no method test [closed]
(3 answers)
Closed 7 years ago.
var r = new RegExp('^[0-9]*$');
function validatePIN (pin) {
//return true or false
if(r.test(pin) && pin.length == 4 || pin.length == 6){
return true;
}else{
return false;
}
}
console.log(validatePin(3627i1));
What's wrong with my regex above? I expect true in this case.
Nothing much is wrong but these conditions will not evaluate correctly:
r.test(pin) && pin.length == 4 || pin.length == 6
As it effectively means (r.test(pin) && pin.length == 4) || pin.length == 6 due to && at higher operator precedence than ||.
You need to enclose conditions in parentheses:
r.test(pin) && (pin.length == 4 || pin.length == 6)
btw you don't even need to check for length afterwards as you can do that in regex itself:
var r = /^[0-9]{4}(?:[0-9]{2})?$/
Now this regex will match either 4 digit number or a six digit number.
validatePin is not the same as validatePIN and 3627i1 is not the same as '3627i1'.
So make sure that you are calling the correct function and passing it a correct argument:
console.log(validatePIN('3627i1'));
syntax errors in your code,
var r = new RegExp('^[0-9]*$');
function validatePIN (pin) {
//return true or false
if(r.test(pin) && pin.length == 4 || pin.length == 6){
return true;
}else{
return false;
}
}
console.log(validatePIN("3627i1")); //call valid function, parameter = string

Location.pathname.indexOf not working with 'Or' ( || )

I'm trying to use location.pathname.indexOf to make conditional jQuery work on some pages on my site.
This works:
if (location.pathname.indexOf("/example/5820.htm") != 0){}
This works:
if (location.pathname.indexOf("/example-1/3569.htm") != 0) {}
This doesn't work:
if (location.pathname.indexOf("/example/5820.htm") != 0 || location.pathname.indexOf("/example-1/3569.htm") != 0) {}
I've done this a ton of times and for some reason this code is not working. I'm wondering if I'm missing something little in the code or if it's something else?
Tim already answered this question, but don't forget:
.indexOf() will return -1 when the string isn't found, not 0.
if (location.pathname.indexOf("/example/5820.htm") != 0){}
Should be:
if (location.pathname.indexOf("/example/5820.htm") != -1){}
Or:
if (location.pathname.indexOf("/example/5820.htm") >= 0){}
http://www.w3schools.com/jsref/jsref_indexof.asp
basically you're saying this:
var a = 0;
var b = 1;
if (a != 0 || b != 0) {};
Which is equal to
if (!(a == 0 && b == 0)) {};
However, you actually want this:
if (!(a == 0 || b == 0)) {};
Which is equal to:
if (a != 0 && b != 0) {};

What is the correct syntax for this 'OR' and 'AND' in this 'IF' statement?

I've got an 'if' statement and just wanted to know if these are both valid (which I believe they are) and if so what is the difference?
var type;
var type2;
if ((type == 'BOS'|| type == 'BPS'|| type == 'BRS') && (type2 == 'BOS'|| type2 == 'BPS'|| type2 == 'BRS))
OR
if ((type == 'BOS') || (type == 'BPS') || (type == 'BRS') && (type2 == 'BOS') || (type2 == 'BPS') || (type2 == 'BRS'))
Which has the correct syntax and do they do anything differently? is there a way to shorten this statement?
Thanks
The two statements are different. Yes, they are both valid statements, syntactically, but logically they differ. Since the && operator has a higher precedence than the || in javscript,
the resulting logic will evaluate as follows in statement 2:
1) (type == 'BRS') && (type2 == 'BOS')
2) (type == 'BOS') || (type == 'BPS') || (result of 1) || (type2 == 'BPS') || (type2 == 'BRS')
While in statement 1:
1) (type == 'BOS'|| type == 'BPS'|| type == 'BRS')
2) (type2 == 'BOS'|| type2 == 'BPS'|| type2 == 'BRS')
3) (result of 1) && (result of 2)
var type1;
var type2;
var correct_value = {
BRS: 1,
BOS: 1,
BPS: 1
};
if( correct_value[type1] && correct_value[type2]) {
alert('ok');
}
else {
alert('not ok');
}
Both conditional statement are valid but the result may be different.
The first statement will evaluate the OR value in the first bracket, and then evaluate the OR value in the second bracket, and finally evaluate the AND operator.
The second statement will evaluate the AND first and then evaluate from left to right without specific precedence (as in the first one).
You have to know which one do you actually use to determine the best refactoring code for it.
See this link: Operator Precedence.

Categories