Search code examples
javascriptnode.jswhile-loopconditional-statements

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{}.

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.