Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to run conditional statement after all comparison operator done

I’m new on programming.

I want to make conditioonal statmenet using if,else inside of while loop.

  while(i < files.length){

         

            if(pathnameParams == files [i]){
                res.sendFile(path.join(__dirname+'/pages/'+pathnameParams.id));
                response.writeHead(200);
                response.end;
            }else{
                res.writeHead(404);
            };

        i++;

        }

but I want to response 404 after all conditional statment done such as all loop are false then run else{}.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

thank you all 🙂

>Solution :

You can use a boolean flag to store whether or not a match was found in the loop.

let found = false;
while (i < files.length) { // note: this can be replaced with a for loop
    if (pathnameParams == files[i]) {
        // ...
        found = true;
        break;
    }
    i++;
}
if (!found) res.writeHead(404);

If this is inside a function, you can also return when a match is found and handle 404 after the loop.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading