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

We need to do exit; after redirecting to php because exit; doesn't stop the rest of the code. But why don't we do something similar 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 this? If not?

+5
source share
1 answer

Why do we need to execute exit(); after redirecting in php?

When you do

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

As php manual on header says , header () is used to send the raw HTTP header. Therefore, it does not stop script execution. It sends the response header associated with the redirect back to the browser and continues to execute the code below. Thus, exit() prevent this.

Do we need return; after calling window.location?

The JS code tells the browser to go to a different URL. Therefore, when navigation is complete. The browser goes to a new page, and the code below window.location will not be executed, unlike the php behavior described above. Therefore, we do not require this.

+4
source

Source: https://habr.com/ru/post/1203457/


All Articles