Why do I get these errors with my ternary operator? - javascript

This is what I get in the console: Unnecessary use of boolean literals in conditional expression no-unneeded-ternary.
I'm just trying to do a ternary operator that validates the state of a game and only if the game has started and the user.role is equal with player I disable the button. I am using reactjs and with the help of FormField hook I am making a form.
disabled ={(game.state === 'started' && user.role === PLAYER) ? true : false}

The ternary operator is unnecessary:
disabled ={(game.state === 'started' && user.role === PLAYER)}

No need to use statements in this case, ESlint is letting you know it's redundant since the value produced from this statement is already a boolean and you can create a simpler code.
Just write:
disabled = {(game.state === 'started' && user.role === PLAYER)}

Related

Better way to write ngClass condition

I am trying to think of a cleaner way to write this condition:
[ngClass]="{
'class1':
image.isAvailable && (image.property !== true && !null),
'class2':
image.isAvailable && (image.property === true && !null)
}"
So image.property sometimes can be NULL, and I am trying to handle it...I know I'm missing something obvious but don't know what. Any help much appreciated
You could use safe navigation operator ?. with ternary operator.
[ngClass]="(image?.isAvailable && image?.property) ? 'class1' : 'class2'"
Safe navigation operator checks if a property is defined before trying to access it.
Update
OP's requirement - use neither of the classes if image?.isAvailable is undefined.
You could extend the ternary operator to one more level to check if image?.isAvailable is defined before applying the classes.
[ngClass]="image?.isAvailable ? (image?.property ? 'class1' : 'class2') : ''"
The empty string '' denotes empty class list if image?.isAvailable property is undefined.
This can be written like this:
[ngClass]="{
'class1':
image.isAvailable && !image.property),
'class2':
image.isAvailable && image.property)
}"
Also you can write like this:
[class.class1]="image.isAvailable && !image.property"
[class.class2]="image.isAvailable && image.property"

Array push with ternary operator

I want to push an error message to a field if it is invalid.
this code works
let message = [];
if (!isvalid) {
message.push("Please enter a value");
}
How can I achieve this with ternary operator.
The way I did.
message.push((!isvalid) ? "Please enter a value" : null)
But this code is also pushing null to the array.
like:: message=[null]
Honestly, it's not a good way to do it. It does not make sense to use a ternary where one logical branch of the condition leads to ...do nothing. Ternary only makes sense where you want to return one of two values depending on the condition.
If you want to be concise you could use:
!isValid && message.push('foo');
though some linters won't like you for it. It has the disadvantage that it is less readable than a simple if. If you must use the ternary, you could also do this:
!isValid ? message.push('Please enter a value') : void 0; // or null
but it's ugly and bad because of that useless hanging false branch of the ternary expression. Don't do it.
Can you try (!isvalid) ? message.push("Please enter a value") : null ?

Boolean and text field validation - Javascript

I have a form that posts to itself with a text field (for SMS number) and a boolean field (for SMS opt in). I can't seem to get the syntax correct for validation when the end-user goes to post the form.
If they select the bool for opt in, then the form should check the text field for the sms number and if the sms number is empty, display an error.
Here's my javascript snippet:
if (document.getElementById("smsOpt").checked = 'true' && document.getElementById("smsNum").value = ''){
error += "smsOpt";
document.getElementById("smsOpt").focus();
document.getElementById("smsOptError").style.display='block';
}
You can do something like this:
if (document.getElementById("smsOpt").checked && document.getElementById("smsNum").value.trim() == ''){
error += "smsOpt";
document.getElementById("smsOpt").focus();
document.getElementById("smsOptError").style.display='block';
}
For checkbox, the checked property is of type boolean so use of only "checked" is fine. And for the second property you can compare it with an empty string. Single = operator in JS is for assignment and not comparison.
You have to use == or === instead of = in vary conditions.
if (document.getElementById("smsOpt").checked == 'true' && document.getElementById("smsNum").value == ''){
error += "smsOpt";
document.getElementById("smsOpt").focus();
document.getElementById("smsOptError").style.display='block';
}
There is actually no need for using any equality operators in this case. You can do something like this:
if (document.getElementById("smsOpt").checked && !document.getElementById("smsNum").value){
error += "smsOpt";
document.getElementById("smsOpt").focus();
document.getElementById("smsOptError").style.display='block';
}
But if you want to use them, then do it with triple === or double equality == operators. You can check the differences between theese two here.
In JavaScript = is only for assignment, so your if-statement is setting checked=true on the input rather than checking what is it. (Or it actually sets it to true no matter what it was and then evaluates the result of setting the value which will always be true)
You need to use == or better ===
if (document.getElementById("smsOpt").checked === true && document.getElementById("smsNum").value.trim() === '') {
I added trim() also so it ignores if you just insert spaces.

How to make true && false equal to true in angularjs expression?

I'm trying to check if an input has been touched and is empty (without the built in functions in angular).
<form-input is-invalid-on="isTouched && !gs.data.name || gs.data.name.length > 50"></form-input>
If isTouched && !gs.data.name evaluates to true && false then that side of the expression becomes false
So my question is quite simple, how do I make the entire expression evaluate to true if the input has been touched and if it's empty or has a length greather than 50?
I believe it is used as attribute directive.
is-invalid-on="(isTouched && gs.data.name.length) || gs.data.name.length > 50"
Reason? I assumed your gs.data.name is a string. Empty string when evaluated in javascript is still a truthy value. So you must evaluate it to length.
<form-input is-invalid-on="(isTouched && !gs.data.name) || (gs.data.name.length > 50)"</form-input>
can try using () and also check gs.data like isTouched && (!gs.data || !gs.data.name || !gs.data.name.length || gs.data.name.length > 50)
<form-input is-invalid-on="isTouched && (!gs.data || !gs.data.name || !gs.data.name.length || gs.data.name.length > 50)"></form-input>
Angular expression does not work exactly the same than javascript from what i got try this one :
<form-input is-invalid-on="isTouched && gs.data.name.length==0 || gs.data.name.length > 50"></form-input>
Assuming you properly initialized gs.data.name to empty string.
By the way you forgot the > on your tag.
I finally found the reason as to why it was behaving so strange, and as this question has many answers I could not delete it. So I might as well explain what happened.
It turned out that isTouched was always undefined because I was using it outside of the directive (even if it was used in an attribute of the directive) which made the expression undefined && false, resulting in isInvalidOn always being false.
Instead I made it so that I used isTouched later in the actual form-input template as ng-class={invalid: isInvalidOn && isTouched}, resulting in the desired behavior.

JavaScript syntax for multiple condition checking

I want to write a JS condition to disable the save button for the following condition;
if status is CLOSED OR
if my model does not have BOTH UPDATE_GLOBAL and UPDATE_LOCAL privilege
I have written the following code;
if ((self.model.get("status") === "CLOSED") || (!self.model.hasPrivilege("UPDATE_GLOBAL") && !self.model.hasPrivilege("UPDATE_LOCAL"))) {
$("#save").attr("disabled", true);
}
Is this the best optimized code? Also are there any unnecessary parentheses (which always confuses me)?
You've said
if my model does not have BOTH UPDATE_GLOBAL and UPDATE_LOCAL privilege
...but that's not what that part of the condition is checking. It's checking if you don't have both; if you have just one, the check result is incorrect.
If you want the button disabled for status = CLOSED or your model doesn't have both privileges, then:
if (self.model.get("status") === "CLOSED" || !(self.model.hasPrivilege("UPDATE_GLOBAL") && self.model.hasPrivilege("UPDATE_LOCAL"))) {
$("#save").attr("disabled", true);
}
Also are there any unnecessary parentheses (which always confuses me!!)
Yes, you don't need the parens around self.model.get("status") === "CLOSED" (but they're harmless).
Also note that your code never enables the button, it just disables it or leaves it alone. If you also want to enable it when the condition for disabling isn't true, then:
$("#save").attr("disabled", self.model.get("status") === "CLOSED" || !(self.model.hasPrivilege("UPDATE_GLOBAL") && self.model.hasPrivilege("UPDATE_LOCAL")));
or (easier to debug):
var flag = self.model.get("status") === "CLOSED" || !(self.model.hasPrivilege("UPDATE_GLOBAL") && self.model.hasPrivilege("UPDATE_LOCAL"));
$("#save").attr("disabled", flag);
I would put it like that:
if (self.model.get("status") === "CLOSED" || !(self.model.hasPrivilege("UPDATE_GLOBAL") && self.model.hasPrivilege("UPDATE_LOCAL")))

Categories

Resources