user1906399
user1906399

Reputation: 771

Why don't we exit/die a script after redirect in Javascript?

We need to do exit; after redirect in php because exit; doesn't stop the rest of the code from running. But why we don't do something like that in javascript. I want to do something like

if(window.location.replace("http://something.com")){
  return;
}

or

window.location.replace("http://something.com");
throw "stop the execution.";

Do i need to do that ? If not why?

Upvotes: 5

Views: 3297

Answers (1)

Mithun Satheesh
Mithun Satheesh

Reputation: 27855

Why we need to do exit(); after the redirection in php?

When you do

header( "Location: ./somepage.php" );

As php manual on header says, header() is used to send a raw HTTP header. So it doesnt stop the script from executing further. It sends the response header related to redirection back to browser and continues executing the code below that. So exit() would prevent doing that.

Do we need return; after the window.location calls?

The JS code says the browser to navigate to another url. So when the navigation is done. The browser navigates to new page and the code below the window.location will not be executed unlike the php behaviour explained above. So we dont require it.

Upvotes: 5

Related Questions