I am wondering if it is correct to write in this way and am I using the brackets correctly?
*This is a code for a country redirects pop-up. The countryCode var is the country of the user (detected by API) while the localStorage.country is which country the user is in on the website.
Feel free to ignore the logic, I just need to know if IF Statement can be written in this way.
if((countryCode == 'sg/' && localStorage.country != "sg/") ||
(countryCode == 'ie/' && localStorage.country != "ie/") ||
(countryCode == 'my/' && localStorage.country != "my/")){
/** Country Redirect Pop Up **/
}
Yes, it is valid and could also be written this way:
let acceptedCountryCodes = ['sg/', 'ie/', 'my/'];
if(countryCode !== localStorage.country && acceptedCountryCodes.includes(countryCode)){
/** Country Redirect Pop Up **/
}
Sure, the code has no problem... It will check if 1st option OR 2nd option OR 3rd option is true
The code currently has no problem!
The wrapping brackets are NOT required in this case because AND(&&) operator has higher precedence than OR(||) operator.
Take a look at the following example:
false && true || false && true = false
The above example is similar to (false && true) || (false && true) which simplies to false || false therefore the final result is false.
Related
I have 3 input fields with text. I want to use an if statement with logical operators to check if any of the input fields are blank, but I can't use or(||) for the 3 variables.
What is the right way to use logical operators?
let name = $("#name").val();
let email = $("#email).val();
let color = $("#color).val();
if(name == '' && ( email == '' || color == '') {
console.log("please complete form");
}
else {
//submit data
}
the code works as desired if I leave the name field blank, but because name is true the if statement accepts it. How can I make it so the if statement checks if any of the input fields are blank?
Use || for each:
if(name === '' || email === '' || color === '') {
You don't need the () groupings because the order of operations doesn't matter - you just want to see if any of the tests succeed.
Note that strict equality comparison (===) is pretty much always preferable over abstract equality comparison (==).
Because .val() always returns a string, and you want to check against the empty string, you could just check whether the value is truthy or not, if you wanted:
if(!name || !email || !color) {
An empty string is considered 'falsy' meaning it is interpreted as false when using logical operators. Using that knowledge combined with the ! (not) operator, we can do this:
if(!name || !email || !color) {
console.log("please complete form");
}
That condition, in plain English, means something like "if not name or not email or not color"
You had a syntax error (forgot a parenthesis in the if statement).
let name = $("#name").val();
let email = $("#email).val();
let color = $("#color).val();
if(name == '' && ( email == '' || color == '')) {
console.log("please complete form");
}
else {
//submit data
}
I am new to Javascript as well as Jquery , but can not figure out what I am doing wrong. I just want to check if the user is on any of 3 URLs. I just want to check if the user is on either the ABOUT US, MEMSTAFF TEAM or CAREERS sections. That is it. I thought that if I just used the OR (||) operator, this should work. What am I doing wrong?
<script type="text/javascript">
$(document).ready(function() {
// Check if any of these relative URLS are true
if(window.location.href.indexOf("/about-us" || "/memstaff-team" || "/careers") > -1) {
// Alert me if I am in one of the MAIN sections
alert("Your are in one of the MAIN sections");
}
});
</script>
The test
if (window.location.href.indexOf("/about-us" || "/memstaff-team" || "/careers") > -1)
is equivalent to doing
temp = "/about-us" || "/memstaff-team" || "/careers";
if (window.location.href.indexOf(temp) > -1)
Since the || operator just returns the first truthy value, it's effectively doing temp = "/about-us" and just testing for that. "OR" expressions aren't automatically distributed, you need to do it explicitly.
if (window.location.href.indexOf("/about-us") > -1 ||
window.location.href.indexOf("/memstaff-team") > -1 ||
window.location.href.indexOf("/careers") > -1)
But a simpler way is to use a regular expression:
if (window.location.href.match(/\/(about-us|memstaff-team|careers)/))
Here is another way of doing it:
const urls = ["/about-us", "/memstaff-team", "/careers"];
if (urls.some(url => window.location.href.indexOf(url) > -1)) {
alert("...");
}
I am writing one small function which validates one text, and I am very upset because of the validation.
The problem is: when I try to compare the string to null (to check the cancel button), it works depending on where I put the condition! It seems to be working only when I put at the beginning of the validation. I have tested it with parenthesis for each condition too, but I get the same result.
What´s happening here?
I found this answer on Stack Overflow, but it is for Python and I don´t understand it very well:
Does the Order of Conditions affect Performance?
Code
function validate()
{
var isValid = false;
var text;
while (isValid == false)
{
text = prompt("Enter one text between 1 and 10 characters, no empty, blank spaces, only numbers");
/*
WITH NULL (CANCEL BUTTON) VALIDATION AT THE BEGINNING,
IT WORKS:
*/
if (text != null &&
(text.length >= 1 && text.length <= 10) &&
text != "" &&
isNaN(text) == false)
{
isValid=true;
}
/*
WITH NULL (CANCEL BUTTON) VALIDATION AT ANOTHER POSITION, IT DOESN´T WORK:
It generates "TypeError:Text is null"
*/
if ( (text.length >= 1 && text.length < 10) &&
isNaN(text) == false && text != "" && text !=null)
{
isValid = true;
}
}
if (isValid == true)
{
// Some code when validation is OK
}
}
You want to check if the text is not null first, because if that condition fails, the rest of the conditions will not be evaluated, since the && invariant has been violated. If the text is null, and the null check comes after some other check, you will receive an error.
Because let's say that we had the following values:
var text = 'Tim is an alright person',
notText = null
If we try to access a property of notText, we will get an error because null doesn't have a properties like length. So, in code:
if(text.length){...}
works because text has a length property. However, the following does not work:
if(notText.length){...}
because notText does not have a length property. It will throw the error of TypeError because you are trying to do something with the null type that is not allowed.
So, we need the text != null check first because it will fail early, before trying the other expressions.
In simple words:
If you evaluate text.anyproperty == null you're asking if the anyproperty of the var text is null, but this way you are taking for granted that text is not null, which will fail with the error you mentioned (TypeError) if text is actually null.
In order to avoid this pitfall you must ask first for text and then for text.anyproperty like this: if(text != null && text.anyproperty != null) ... so, this way, if text != null fails, the text.anyproperty != null will not be evaluated and you won't get the TypeError.
For the purpose of your validation, using if(text != null && text.anyproperty != null) you can achieve your goal, since if text is null, it doesn't make any sense check text.anyproperty (that's why the rest of the expression, the code after &&, is not evaluated).
Hope this help you understand better this matter :)
When I make a conditional on jQuery that specifies to make something if an input OR a select list is empty, jQuery works fine:
if((($('input[name=su_name]').val())=="") || ($('select[name=su_family]').val())=="0")
{...}
But when I try to make it check 3 fields (if one, or the other, or the other is empty), I have a syntax error focusing the second "||". Is it not possible to set two "||" (OR) on the same conditional? This does not work:
if((($('input[name=su_name]').val())=="") || ($('select[name=su_family]').val())=="0") || ($('input[name=su_abbrev]').val())=="")
{...}
I don't know why you're using so many parenthesis in that second example, but this should work:
if ( $('input[name=su_name]').val() == "" || $('select[name=su_family]').val() == "0" || $('input[name=su_abbrev]').val() == "" )
You've used so many redundant (), instead you can just do:
if ($('input[name=su_name]').val() == "" || $('select[name=su_family]').val() == "0" || $('input[name=su_abbrev]').val() == "") {
// Your code here
}
Code:
if (!IDTextField.value && !FirstNameField.value &&
!LastNameField.value && !DateOfBirthField.value!GenderField.value) {
alert('No criteria Added');
return;
}
The alert is not called when all the text fields are blank.
You're missing the && between the last two criteria
It should be:
if (!IDTextField.value && !FirstNameField.value &&
!LastNameField.value && !DateOfBirthField.value && !GenderField.value)
In cases like this, it makes a lot of sense to format your if statement like this:
if ( !IDTextField.value
&& !FirstNameField.value
&& !LastNameField.value
&& !DateOfBirthField.value
&& !GenderField.value)
If you do it this way, you can't make the mistake you just made.
xbonez got it right. You are missing && between last two expression.
For something not so important, I would like to get all expressions evaluated using || and then add negation using !, rather than negating all expression and evaluate them with &&. This can make this expression a little faster, if am not wrong.
if (!(IDTextField.value || FirstNameField.value ||
LastNameField.value || DateOfBirthField.value || GenderField.value)) {
alert('No criteria Added');
return;
}
Tell me what you all think??
What is this little abomination?
... !DateOfBirthField.value!GenderField.value
I think that should be:
... !DateOfBirthField.value && !GenderField.value
You should write your code like this
if (!IDTextField.value && !FirstNameField.value &&
!LastNameField.value && !DateOfBirthField.value && !GenderField.value) {
alert('No criteria Added');
return;
}
You're missing the && between the last two criteria
the && is missed ,add it and try ,should work if no other errors exist