if statement executes code under wrong condition - javascript

I have a simple code with a if statement as follows:
if ((marker.category == str || $("#type").length === 0)
&& (marker.session == session || session.length === 0)) {
marker.setVisible(true);
console.log("session"+session);
} else if (marker.session == session || session.length === 0) {
marker.setVisible(true);
} else {
marker.setVisible(false);
infowindow.close(map, marker1);
}
If I run this code, it always executes the else if condition, but I think the if and else if conditions are different, how to solve this problem? I know the if and else if may have a part of same conditions but with operator && it should be different, right? It has really confused me.

It's quite odd to repeat part of a logical AND in an else if condition. I feel you may be able to understand this better if you refactor the common parts out.
For example
if (marker.session == session || session.length === 0) {
marker.setVisible(true); // same for first two conditionals
if (marker.category == str || $("#type").length === 0) { // &&
console.log("session", session);
}
} else {
marker.setVisible(false);
infowindow.close(map, marker1);
}
If you don't see that console.log(), it clearly means the
marker.category == str || $("#type").length === 0
expression is evaluating as false.
You could even simplify this further by re-using the same boolean values where required. This can eliminate the else blocks which can aid readability. I also think it's odd to conditionally log something so just log it anyway.
let sessionVisible = marker.session == session || session.length === 0
marker.setVisible(sessionVisible)
console.log("session", session);
if (!sessionVisible) {
infowindow.close(map, marker1);
}

if (marker.session == session || session.length == 0) {
marker.setVisible(true);
if (marker.category == str || $("#type").length == 0) {
console.log("session"+session);
} else { }
} else {
marker.setVisible(false);
infowindow.close(map, marker1);
}

this is solved, with this code
if ( (marker.session == session || session.length === 0) && (marker.category == str)){
marker.setVisible(true);
}else if( (marker.session == session || session.length === 0) && (str.length === 0)){
marker.setVisible(true);
}else {
marker.setVisible(false);
infowindow.close(map, marker1);
}
}
that is seem like same condition but different, thanks for you all to help me

Related

If else condition not working for string comparision in JS [duplicate]

This question already has answers here:
Check variable equality against a list of values
(16 answers)
Closed 1 year ago.
I have an if-else condition in js as below and I am expecting else condition to execute for the below logic, because the destination ID is in else if, but it always goes into the if condition. tried with == and === too.
What am I missing?
Note: The logic is to be supported in ie11
// destinationId is generated dynamically but i have assigned it to a variable for reference
Code 1
var fromId = "createNotification";
var destinationId ="detailedDescription";
if ((fromId == "createNotification") && (destinationId == "carNumber" || "setNumber")) {
//logic to execute
} else if ((fromId == "createNotification") && (destinationId == "faultRepBy" || "detailedDescription")) {
//logic to execute
}
code 2
if ((["createNotification"].indexOf(fromId) > -1) && (["carNumber" || "setNumber"].indexOf(destinationId) > -1)) {
//logic to execute
} else if ((["createNotification"].indexOf(fromId) > -1) && (["faultRepBy" || "detailedDescription"].indexOf(destinationId) > -1)) {
//logic to execute
}
Change your condition as below:
if ((fromId == "createNotification") && (destinationId == "carNumber" || destinationId == "setNumber")) {
console.log("in if")
} else if ((fromId == "createNotification") && (destinationId == "faultRepBy" || destinationId == "detailedDescription")) {
console.log("in else if")
}

logic in if/else method in javascript

i just want to implement if else method in my apps
the problem is when in choose the first if it working, but if i choose second if its not working, this is my code
//filter in session
filterMarkersx = function (session) {
var table = $('#edcTable').DataTable().column(1).column(2);
var str;
$("select#type option:selected" ).each(function() {
str = $(this).val();
});
for (i = 0; i < gmarkers1.length; i++) {
marker = gmarkers1[i];
if(marker.session == session || session.length === 0) {
marker.setVisible(true);
} else if(marker.session == session || session.length === 0) {
if (marker.category == str || $("#type").length === 0){
marker.setVisible(true);
}
}else{
marker.setVisible(false);
infowindow.close(map, marker1);
}
}
table.search(str).draw();
}
anyone can help me what must i do, thanks in advance.
-kraken.
Your if and else if conditionals are exactly the same. The else if block can never execute, since if its conditional is true, then the first if is true, so its else isn't even looked at.

If statements and conditions

I am trying to confirm two different things in an alert box, if statement. The first is that the user pressed the yes button and the second is a user input value on the page. See the code below. I'm still pretty green, any help would be greatly appreciated.
var cMsg = "You are about to reset this page!";
cMsg += "\n\nDo you want to continue?";
var nRtn = app.alert(cMsg,2,2,"Question Alert Box");
if(nRtn == 4) && (getField("MV").value == 5)
{
////// do this
}
else if(nRtn == 4) && (getField("MV").value == 6)
{
/////then do this
}
else if(nRtn == 4) && (getField("MV").value == 7)
{
/////then do this
}
}
else if(nRtn == 3)
{
console.println("Abort the submit operation");
}
else
{ //Unknown Response
console.println("The Response Was somthing other than Yes/No: " + nRtn);
}
Your if...else syntax is incorrect. Correct syntax
if (condition)
statement1
[else
statement2]
Use correct syntax
if (nRtn == 4 && getField("MV").value == 5) {
////// do this
} else if (nRtn == 4 && getField("MV").value == 6) {
/////then do this
} else if (nRtn == 4 && getField("MV").value == 7) {
/////then do this
} else if (nRtn == 3) {
console.println("Abort the submit operation");
} else { //Unknown Response
console.println("The Response Was somthing other than Yes/No: " + nRtn);
}
instead of
if (nRtn == 4) && (getField("MV").value == 5) {
////// do this
} else if (nRtn == 4) && (getField("MV").value == 6) {
/////then do this
} else if (nRtn == 4) && (getField("MV").value == 7) {
/////then do this
} <=== Remove this
} else if (nRtn == 3) {
console.println("Abort the submit operation");
} else { //Unknown Response
console.println("The Response Was somthing other than Yes/No: " + nRtn);
}
you are trying to evaluate two different conditions that is:
"nRtn" // value returned from app.alert(cMsg,2,2,"Question Alert Box");
and: getField("MV").value.
However, the compiler will only process the first condition because the braces end there. You should make sure to enclose all conditions within one brace. Individual conditions can and by convention should be in separate braces too within the main brace.
The right way therefore should be:
if ((nRtn == 4) && (getField("MV").value == 5))
//notice the initial if (( and terminating ))
//You could have 3 conditions as follows
// if (((condition1) && (condition2)) && (condition3)))
{
////// do this
}
else if((nRtn == 4) && (getField("MV").value == 6))
{
/////then do this
}
else if((nRtn == 4) && (getField("MV").value == 7))
{
/////then do this
}
}
else if(nRtn == 3)
{
console.println("Abort the submit operation");
}
else
{ //Unknown Response
console.println("The Response Was somthing other than Yes/No: " + nRtn);
}

What is simpler way to achieve an if then else if else stack in javascript

Is there a way to simplify this or a more terse form i can use? The logic contained is all correct. It just seems like a lot of returns and else ifs.
mode = (function(mode, current, proposed, origins, destinations) {
if (mode === 'none') {
return 'project';
} else if (proposed.count === 0) {
return 'unseated';
} else if (current.count > proposed.count && proposed.count > 0) {
return 'reducing';
} else if (proposed.count === destinations.count && destinations.count > 1 && current.count === 0) {
return 'newplus';
} else if (proposed.count === destinations.count && current.count === 0) {
return 'new';
} else if (proposed.count > destinations.count) {
return 'increasing';
} else if (proposed.count === destinations.count && destinations.count > origins.count) {
return 'moveplus';
} else {
return 'move';
}
}(moves.register[staff].move, {count: mode.currentDesks}, {count: mode.proposedDesks}, {count: mode.origins}, {count: mode.destinations})));
I previously used a nested ternary which is marginally shorted but i would argue more prone to error and difficult to read (the results are marginally different due to code evolution not errors in replication):
mode =
(moves.register[staff].move === 'none') ? 'project' :
(mode.proposedDesks === 0) ? 'unseated' :
(mode.currentDesks > mode.proposedDesks && mode.proposedDesks > 0) ? 'reducing' :
(mode.proposedDesks === mode.destinations && mode.destinations > 1 && mode.currentDesks === 0) ? 'newplus' :
(mode.proposedDesks === mode.destinations && mode.currentDesks === 0) ? 'new' :
(mode.proposedDesks > mode.destinations) ? 'additional' :
(mode.proposedDesks === mode.destinations && mode.destinations === mode.origins) ? 'move' :
(mode.proposedDesks === mode.destinations && mode.destinations > mode.origins) ? 'moveplus' :
'other';
So while I like the if…then…elseif stack for legibility, it feels like it is more verbose than it could be. I don't think i'm looking for a switch…case version doesn't quite cut it due to the number of comparison variables, and it feels wrong to nest if statements within a switch…case or ternary operators within an if…then…else.
I think instinctively i'd like a form of matrix where the return values are in a grid and somehow a matrix calculation of the the various bitwise conditions returned the correct result. I suspect though that would be a win of compact code over legibility.
Any suggestions?
NB. The variable names including the addition of a count property to each instead of naming the variable as such or not indicating that it is a count are chosen for legibility.
you can use a var to store your choice and return it at the end
mode = (function(mode, current, proposed, origins, destinations) {
var varName='move';
if (mode === 'none') {
varName='project';
} else if (proposed.count === 0) {
varName='unseated';
} else if (current.count > proposed.count && proposed.count > 0) {
varName= 'reducing';
} else if (proposed.count === destinations.count && destinations.count > 1 && current.count === 0) {
varName= 'newplus';
} else if (proposed.count === destinations.count && current.count === 0) {
varName='new';
} else if (proposed.count > destinations.count) {
varName= 'increasing';
} else if (proposed.count === destinations.count && destinations.count > origins.count) {
varName= 'moveplus';
}
}(moves.register[staff].move, {count: mode.currentDesks}, {count: mode.proposedDesks}, {count: mode.origins}, {count: mode.destinations})));

simplify if .. else in javascript

my mind is blank and I can't think of the solution...
I have the following code:
if (onlySelected === true) {
if (r.selected == true) {
result.push(pushValue);
}
}
else {
result.push(pushValue);
}
how can I simplify this code into this:
if (condition) { result.push(pushValue) }
Try this:
if (!onlySelected || r.selected){
result.push(pushValue);
}
or this if you absolutely need the type equality and not just truthiness:
if (onlySelected !== true || r.selected){
result.push(pushValue);
}
if(onlySelected === false || r.selected == true) {
result.push(pushValue);
}
(!onlySelected || r.selected) && result.push(pushValue);
if( (onlySelected === true && r.selected === true) || 1) {
result.push(value)
}
I think this would work:
if(!onlySelected || (onlySelected && r.selected))
result.push(pushValue);
Hm, this is what I made it to.
onlySelected === !0 ? r.selected == 1 && result.push(pushValue) : result.push(pushValue)

Categories

Resources