8

What is the equivalent of PHP's exit; in Javascript/jQuery?

I need to stop my script early depending on certain conditions... The only answers I could find from search was stopping forms from submitting...

Jamesking56
  • 3,683
  • 5
  • 30
  • 61
  • possible duplicate of [How to terminate the script in Javascript](http://stackoverflow.com/questions/550574/how-to-terminate-the-script-in-javascript) – Dennis Traub Sep 04 '12 at 10:47
  • In PHP, exit() can be called anywhere. In JavaScript, return can only be called in a function, not in file scope. – David Spector Nov 24 '18 at 16:16

4 Answers4

14

You could try:

throw "stop execution";

Using return you will skip the current function, that's why throwing is more similar to PHP exit();

arutaku
  • 5,937
  • 1
  • 24
  • 38
3

I would finish a function early with a return statement:

return;
Florian Bauer
  • 626
  • 3
  • 12
2

A javascript function is terminated by calling return. Usually you will be in the context of a function or something. Also event handlers (like for onclick on an element) will behave like a function and accept return.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
1

From looking on your certain problem, and for everyone else. Please see this. This MIGHT help you.

Just put this one line

if(exit_condition!=true)

and also this requires your codes to be inside of

$(document).ready()

if(exit_condition!=true)
    $(document).ready(function() {
      // Your code
      // Your code
      // Your code
      // Your code
    });

I have also encountered this issue, @Jamesking56 has encountered. And this is my solution.

Jovylle
  • 859
  • 7
  • 17