How to exit or break out from an else if - javascript

I've searched for a couple stackoverflow questions although couldn't find my answer.
I'm trying to break from an else if statement and was wondering if there was a more efficient way.
Heres a snippet:
var argument = "something";
if(argument == 'not_this'){
// this doesn't trigger
} else if(argument){
// this triggers although if the functions in here doesn't match what I want,
// how do I make It skip to the else statement without adding another else
// if statement?
} else {
// do something if both statements above fail
}
Is there something that I can do which exits from the else if(argument)... without adding another else statement? I've tried using switch and case although those don't seem to help.
Thanks.

You could set a flag that is by default true, and whenever the argument is valid you set it to false.
Then, to know when to execute the 'else' block, you can just check whether the flag is true or not:
var argument = "something";
let invalid = true
if (argument == 'not_this') {
// this doesn't trigger
invalid = false
} else if (argument) {
if (typeof argument != 'string') {
//valid
invalid = false
}
}
if (invalid) {
console.log('invalid')
}

Restructure the code to avoid confusing states, move out the if 'has value' check.
if (argument) {
if (argument === 'not_this') {
// this doesn't trigger
}
} else {
// do something if both statements above fail
}
For equality, it is safer to use strict equal === instead of loose equal ==

You could try using return; to break out of the statement, as that would stop all other code from being read.

Related

How can I create a fallback for a series of JavaScript if statements?

So I want to do something that would allow me to have a form or text field ( tag in html) and basically I can type something into that field and have something else happen
For example:
if (x === "something") {
then do this set of instructions
}
if (x === "something else") {
then do this different set of instructions
}
else {
alert("Some error message")
}
In the example above, is it possible to do something where I can type "something" and have it do that set on instructions but not show the alert in the else {} statement?
The different sets of instructions are different and the "something" and "something else" are also different, but the x is in reference to the tag which is inside a tag.
But basically if any of the "if" statements are met, do not execute the "else" statement. But if any of the "if" statements are not met, then execute the else statement. Not sure if it's possible, but I have no clue, just started working with js, so sorry if this is a very basic thing.
Use
if(x === "something") {
then do this set of instructions
} else if (x === "something else") {
then do this different set of instructions
} else {
alert("Some error message")
}
Plus, the answer is kind of obvious!
Take a look at the switch statement.
switch(x) {
case 'something': {
do this set of instructions;
break;
}
case 'somethingelse': {
do this other set;
break;
}
default: {
some error message
}
}
This... Is exactly how if statements work if I understood correctly. If a condition is True, execute this set of instructions. If it's not, execute this other set of instructions (alert an error)
Though you might be referring to the else if statement. In this case, else will only run if x isn't equal to something else.
Change the code to:
if (x === "something") {
then do this set of instructions
} else if (x === "something else") {
then do this different set of instructions
} else {
alert("Some error message")
}
And you should be good.
If I'm understanding your wording, you would like to be able to execute any arbitrary number of if statements, and then not execute your else if any of the if statements have been entered. There is not a native built-in logic structure that does this, but it can be easily achieved using a variable in the containing scope that is flipped if any of the if statements is entered:
let enteredAnIf = false;
if (aThing) {
// do some stuff
enteredAnIf = true;
}
if (aDifferentThing) {
// do some different stuff
enteredAnIf = true;
}
if (!enteredAnIf) {
// this is your "else", entered only if none of the above `if`
// statements flips the `enteredAnIf` to `true`
}

How to use break statement in Typescript

I'm new to Javascript. I started with a very basic project in Angular i.e. Form validation. In my case I've to call my custom method, validationTest() within itself only once. If I do not put any break condition then there will be too many recursions. I have to stop this. I tried many other solutions:
Break Statement in TypeScript
TypeScript - Loops
I followed them very carefully, but I'm getting this:
Module parse failed: Unsyntactic break (84:12)
Here's my code:
validationTest() {
let count =0;
this.isAnyRangeInvalid = false;
this.monthpicker.forEach(picker => {
if (picker.isValidRange === false) {
this.isAnyRangeInvalid = true;
}
});
count ++;
if(count===1) {
break;
}
this.validationTest();
}
Even VScode editor is also showing a red zig-zag line under the token break.
I'm coming from Java and CPP background. Please correct me.
To stop a function from executing, use return. break only makes sense in the context of a for or while loop.
But another problem is that your validationTest doesn't have a persistent view of the count variable - it's completely local, so the test isn't going to work anyway. Consider passing a parameter instead, which will indicate whether the current call is recursive or not:
validationTest(lastTry = false) {
this.isAnyRangeInvalid = false;
this.monthpicker.forEach(picker => {
if (picker.isValidRange === false) {
this.isAnyRangeInvalid = true;
}
});
if (!lastTry) this.validationTest(true);
}
Make sure that the initial call of validationTest doesn't pass a parameter, or passes false.
For a more general solution of limiting yourself to N recursive tries, you can pass around a number instead, eg:
validationTest(triesLeft = 3) {
this.isAnyRangeInvalid = false;
this.monthpicker.forEach(picker => {
if (picker.isValidRange === false) {
this.isAnyRangeInvalid = true;
}
});
if (triesLeft !== 0) this.validationTest(triesLeft - 1);
}

Recursive Operation and then jump out of the loop

I have an object which stores department hierarchy. Each department might have sub department as well. I am trying to loop to check all department and also sub(child) department properties are Open.
However, whenever I hit recursive call, it only iterates once and jump directly to return true, even though there are still some items which has not checked in the loop yet.
validateDepartment(departmentHierarchy: any) {
for (let dept of departmentHierarchy.children) {
if (dept!= undefined && dept!= null) {
if (dept.instance.status == "Open")
{
continue
}
else
{
if (dept.children != undefined && dept.children != null) {
this.validateDepartment(dept);
}
else {
return false
}
}
}
}
return true
}
Not part of any answer, but it helps to only write the code that "does" things, rather than having lots of code that does "what the code would already do anyway", such as calling a continue when the iteration code is a single if/else. We can rewrite your code to this, and have something easier to work with:
validateDepartment(tree: any) {
// step 1: do any validation of the top node
if (!validateTopNodeOnly(tree)) {
// this is a stop condition.
return false;
}
if (!tree.children) {
// this is also a stop condition, but for a different reason.
// a department without children should not _necessarily_ be invalid.
return true? return false? probably return true since the node itself is fine.
}
if (tree.instance && tree.instance.status !== "open") {
// and this is a third condition, but for yet another reason.
// I'm guessing this is also not "invalid", just means we shouldn't recurse.
return true? return false? probably return true as well.
}
// Then, get all (non-falsey) children,
let children = tree.children.filter(e => e);
// and iterate over them:
for (let e of children) {
let result = this.validateDepartment(e);
// cut your run short if validation fails
if (result === false) {
return false;
}
}
// and this is the expected stop condition for a normal run.
return true;
}
But using true/false is incredibly naive and won't tell you anything about where validation failed, so you'll want to work in "what failed", typically by returning a reference to the actual "thing that's getting validated" so that if your function returns true, all is well, and it returns something !== true then you know it failed, and the thing it returned is the department where things went wrong.
Also note that by using an early return on validation failure, you're missing out on information: instead it's way better to use .map() and construct a running tally of all deparments that pass/fail validation, so that you return an array in which either result.every(e => (e===true)) is true, or is false, in which case result.filter(e => (e!==true)) gives you the set of every single failed department.
isopen = this.validateDepartment(this.departmentHierarchy);
validateDepartment(dept: any): boolean {
let result=(dept.instance.status == "Open");
if (result) {
if (dept.children) {
dept.children.forEach(x => {
result = result && this.validateDepartment(x)
})
}
}
return result;
}

Why is the if conditional set to !false?

This is taken from another question of mine. Where the code below was given as an answer, though i'm not quite sure what is happening in it.
The aim is to only fetch userid once at the start instead of fetching it everytime fetchupdate() is called.
var delay = 300000, userIdFetched = false;
function GetUpdate(status)
{
if(status == "fail")
{
setTimeout(function(){
fetchupdate();
},delay * 2);<-- need to make this double itself
}
else
{
setTimeout(function(){
fetchupdate();
},delay);
}
};
function fetchupdate(){
var userid=$_SESSION['UserID'];
$.ajax()
{
type:"POST",
url:"getupdates.php",
data:{userid: userid},
complete:function(data,status)
{
if(status == true)
{
if(!userIdFetched){ <----Why is this set to !userIdFetched instead of userIdFetched
userIdFetched = true;
//Get the user Id here
}
$("#Updates").text(data);
GetUpdate("success");//Changed to String
}
else
{
$("#Updates").text("You have no updates.")
GetUpdate("fail");//Changed to String
}
}
}
}
Question:
Why is the if condition set to
if(!userIdFetched)
which evaluates to (!false) --> if(true), which causes the code in the if block to run, after which userIdFetched is set to true?
Shouldn't the if conditional be set to
if(userIdFetched)
which should cause the code in the if block to run, after which userIdFetched would be set to true, to represent the userid being fetched?
I would appreciate someone clarifying this up for me if possible.
No, it should be if(!userIdFetched), because you only need to enter the if-block when userIdFetched is false. If it's true, then there's no need to enter the if-block.
It might help to think of it as being roughly equivalent to:
if(userIdFetched == false)
Although there are some difference in how x == false and !x works with regard to some 'falsey' values (demonstration). In your case, since you're only dealing with Boolean values, this is not an issue.

Check both conditions in an if statement even if the first one is false

I have two statements in an if block that both link to a function that will return a bool. Both statements must be true for the code to run but I want them both to be checked even if the first one is false. The relevant code:
if (myFunc(one) && myFunc(two)) {
//execute
}
myFunc will execute some code before returning false, but this code is not executed on two if one returns false.
I got this to work, but it feels like a hack:
if ((myFunc(one) && myFunc(two)) || (myFunc(two) && myFunc(one))) {
//execute
}
Does anyone have a better solution? Thanks!
Another way:
var first = myFunc(one),
second = myFunc(two);
if (first && second) {
//execute
}
In this case both will be executed first and checked for non false values later.
use the & operator
take a look at this example
function a (){
console.log(1);
return true;
}
function b (){
console.log(2);
return false;
}
if(b() & a() == true){
console.log('asas');
}

Categories