What condition is false in a multiple conditions if statement - javascript

I'm writing a multiple if statement in Javascript. I've 3 (or more) conditions, and I wanna doSomething() only if all these 3 conditions are true. If only one of these 3 are false, I wanna doSomethingElse(). I think my code it's right, but my problem is on another level.
What if I wanna know for which condition my statement is false?
E.g.: condition1=true, condition2=true, condition3=false.
if (condition1 && condition2 && condition3) {
doSomething();
} else {
doSomethingElse();
};
I've thought that I can put another if statement in the else part.
if (condition1 && condition2 && condition3) {
doSomething();
} else {
if (condition1 == false) {
doWhatIDoWhenC1isFalse();
};
};
Is this the right way? Is there any other way to do this? Maybe faster way!
Thank for your help, and be nice to me, it's my second day on Javascript :)

Since the conditions are mutually exclusive, you can just use an else if without nesting.
if (condition1 && condition2 && condition3) {
doSomething();
} else if (!condition1) {
doWhatIDoWhenC1isFalse();
}
// add more else-if conditions as needed
If only one of your conditions can be false at a time (or if you don't care when two of them are false) then you can just have three else-if clauses and check each condition individually. If you do need to treat the cases where two conditions are false separately, you'll need an else-if for each combination. Pay close attention to the order you list them in if that's the case. The cases where you check if two conditions are both false should come before the cases where you only check one condition.

if (condition1 && condition2 && condition3) {
doSomething();
}else if (!condition1){
doWhatIDoWhenC1isFalse();
}else if (!condition2){
doWhatIDoWhenC2isFalse();
}else{
doWhatIDoWhenC3isFalse();
}
You have to do something along the lines of this. No way to cleanly get which expression that failed.

You may go this way if you want if any one of the condition is false:
if ((!condition1 && condition2 && condition3)||
(condition1 && !condition2 && condition3)||
(condition1 && condition2 && !condition3))
{
doSomethingElse();
} else {
doSomething();
};

It can be:
var x = []; /* an array that will take expressions number that result true */
if(condition1) x.push(1);
if(condition2) x.push(2);
if(condition3) x.push(3);
if( x.length == 2 ){ /* if two conditions got true */
doThingForTwoTrue();
}
if( x.length == 3 ){ /* if three conditions got true */
doThingForThreeTrue();
}
if( x.indexOf(1) !== -1 ){ /* if condition1 got true */
doThingOne();
}

Related

issues with localStorage and saving values

I have a program where I have these strings being added to an array. However, there are many strings that are triggered by a certain condition, which can be met multiple times, however I only want it to be added on the first occurrence. So I have implemented a system where the event of adding the string to the array is triggered by the original condition, and a boolean expression. Here is an example of one of those conditions:
if (count >= 10 && displayMulti == true) {
consoleData.shift()
consoleData.push("Multi available")
displayMulti = false
window.localStorage.setItem("display_multi", String(displayMulti))
updateConsole()
}
When the string is added to the array, the boolean, displayMulti, is set to false so that it will not trigger again. However, upon refreshing the page, it will still trigger. I'm not sure why because I feel like I have saving the values to localstorage correctly. Code is below:
if (window.localStorage.getItem("display_multi") != null ) {
displayMulti = Boolean(window.localStorage.getItem("display_multi"))
} else {
console.log("here")
var displayMulti = true
}
There "here" console log statement is not triggered. So I have no idea why this would keep triggering because I don't see how the boolean is true. I've tested at like so many different points I genuinely have no idea what's wrong. I also don't think those values are affected anywhere else in my code. Any help is appreciated.
Here is a solution that properly parses your string as a boolean. Instead of Boolean(), a conditional (window.localStorage.getItem("display_multi") === 'true')(window.localStorage.getItem("display_multi") === 'true') is used.
if (window.localStorage.getItem("display_multi") != null ) {
displayMulti = (window.localStorage.getItem("display_multi") === 'true')
} else {
console.log("here")
var displayMulti = true
}
if (count >= 10 && displayMulti == true) {
consoleData.shift()
consoleData.push("Multi available")
displayMulti = false
window.localStorage.setItem("display_multi", String(displayMulti))
updateConsole()
}

How to simplify the following if statements and ternary operators?

The following code is inside a loop which loops through the fields of a form. If isV1User is true, then the field is disabled. If the user has customSetting then don't disable the field. If the user doesn't have it, disable it.
if (field.name === 'themeColor') {
if (this.isV1User) {
field.disabled = false
} else {
field.disabled = this.user.customSetting
? !this.user.customSetting.themePicker
: false
}
}
How to simplify or at least remove the nesting of this code?
Move every if condition to ternary:
if (field.name === 'themeColor') {
field.disabled = !this.isV1User && this.user.customSetting && !this.user.customSetting.themePicker;
}
if (field.name === 'themeColor') {
field.disabled = this.user.customSetting && !this.isV1User ?
!this.user.customSetting.themePicker : false;
}
This isn't really a Stack Overflow question, would fit better on Code Review I guess.
There's only one set of circumstances in which it needs to be true, it seems, so maybe like this?
if (field.name === 'themeColor') {
field.disabled = (
!this.isV1User &&
this.user.customSetting && !this.user.customSetting.themePicker);
}
The first if is still needed because other fields should remain unchanged (I assume).
You can do like this
"themeColor"===field.name && (field.disabled=this.isV1User?!1:
this.user.customSetting?!this.user.customSetting.themePicker:!1);
The way that you have structured your code, it can be minimized to the following equivalent code. Please note that if this.user.customSetting.themePicker is guaranteed to always be true when this.user.customSetting is true, you can set field.disabled = true in a single if statement where the conditional is field.name == 'themeColor':
if (field.name == 'themeColor' && this.user.customSetting) {
field.disabled = !this.user.customSetting.themePicker;
} else if (field.name == 'themeColor') {
field.disabled = false;
}
Or even the following switch statement, depending on how you want your code structured. They both are the same.
switch (field.name) {
case 'themeColor':
if (this.user.customSetting) {
field.disabled = !this.user.customSetting.themePicker;
}
break;
default:
field.disabled = false;
}
Most of these answers break the cardinal rule of ternary statement readability. If your goal is simplistic readability, breaking it down to a simple if/else if statement will do. If you are trying to minimize the code as much as possible, and don't care if it's unmaintainable/hard to read, you should simplify it to a recursive ternary statement. Personally, I find that long ternary statements do not provide significant space-saving, hamper readability, and should be avoided in cases where they are not extremely simple (ie: var x = statement? 1 : 0;)
Try this
if (field.name === 'themeColor') {
field.disabled = this.isV1User ? true : this.user.customSetting ? !this.user.customSetting.themePicker : false;
}

if statement with more than one condition

I need to check three conditions,
sheet_exists = 1
recalc = 1
qty_total and new_qty_total are not equal
The if statement works well if only the first 2 arguments are used:
if(sheet_exists === 1 && recalc === 'yes'){
//do something
}
But when I try to add he 3rd argument it fails, the actions in the if statement are ignored. I've tried:
if((sheet_exists === 1) && (recalc === 'yes') && (qty_total !== new_qty_total)){
//do something
}
And:
if(sheet_exists === 1 && recalc === 'yes' && (qty_total !== new_qty_total)){
//do something
}
And:
if(sheet_exists === 1 && recalc === 'yes' && qty_total !== new_qty_total){
//do something
}
Where am I going wrong?
Considering you are happy with the behavior of the first two conditions, and not with the last one, the problem must be in the last one.
Pay attention, qty_total !== new_qty_total will return TRUE only when the value or type of qty_total and new_qty_total are different.
If one is an integer 100 and the other is a string '100' then the condition evaluates as TRUE because they differ on the data type. But if they are both integers it will return FALSE, because neither the value nor the type are different.
To make sure the comparison works ok, make sure both variables are the same data type.

Execute If statement, only if element is existed

if($("#Prefix").val().trim()=="" && $("#Infix").val().trim()==""){
return false;
}
In the above code, when the element id Prefix or Infix does not exist, it's throwing undefined error
TypeError: $(...).val(...) is undefined
I know, this can be avoided by checking its length $("#Prefix").lenght>0 and $("#Infix").lenght>0.
My question here is, how can we do both checks inside single if statement itself.
try below code . check this link explain element length condition
if(($("#Prefix").length && $.trim($("#Prefix").val()) == "") && ($("#Infix").length && $.trim($("#Infix").val())=="")){
return false;
}
if (($("#Infix").lenght>0 && $("#Prefix").lenght>0) && ($("#Prefix").val().trim()=="" && $("#Infix").val().trim()=="")){
//your code here
}
Yes you can.
if statement with && operator stops checking farther when first 0 is returned. [0 && anything == 0].
So just check for the .length first.
if ( ($("#Infix").lenght && $("#Prefix").lenght) && (another conditions) ) {
...
}

Is there any way of determining which or statement is true in javascript?

So say I have an if statement:
if(a=='' || b==''){
//which is true?
}
Is it possible to determine which statement satisfied the if statement without doing a switch statement or another if statement to check?
You can define a token to store what condition was true:
var token = null;
if ((a == '' && (token = 'a')) || (b == '' && (token = 'b'))) {
// Here token has an 'a' or a 'b'. You can use numbers instead of letters
}
I think it's the simplest way to do what you want.
As others have said, you have to test the conditions separately, but you can kind of mix worlds.
var test1 = 1 == 1; // true
var test2 = 2 == 1; // false
if (test1 || test2) {
// If either conditions is true, we end up here.
// Do the common stuff
if (test1) {
// Handle test1 true
}
if (test2) {
// Handle test2 true
}
}
No, you have asked explicitly if one or both are true. There's no way to work out which of those sub-expressions is true without another conditional of some sort.
If you're interested in different behaviour based on which is true, you should probably separate them with a possibly-common bit, something like
either = false;
if (a == ' ') {
doActionsForA();
either = true;
}
if (b == ' ') {
doActionsForB();
either = true;
}
if (either) {
doActionsForAorB();
}
If you care about which of the two conditions is true the only way to find out is to test them separately, e.g.
if(a==''){
// ...
}
else if(b=='') {
// ...
}
Sometimes, especially in more complicated conditionals, it helps if you store the result of each condition and reuse it later on:
var isFoo = a == '';
var isBar = b == '';
// You can now use isFoo and isBar whenever it's convenient
the simple solution:
if ((ia=(a=='')) || (b=='')) {
// ia indicate whether the boolean expression a have been true.
// ia -> a has been true, b may have, !ia -> b has been true, a has not
}
there is no ib in the simple solution as it won't be always be set due to shortcut evaluation.
to cater for shortcut evaluation try:
if (((ia=(a=='') || (ib=(b=='')) && ((ib=(b=='')) || (ia=(a==''))) {
// ia, ib indicate whether the corresponding boolean expressions have been true
}
if(a=='' || b==''){
var x= a || b;
//if a is ''(falsy) x will be b, else a
}
var phone="";
var email="something";
if(phone=='' || email==''){
var x= (phone) ? 'phone':'email';
console.log(x); //email
}

Categories

Resources