How to terminate a script in JavaScript ?
Last Updated :
17 Jan, 2024
To terminate a script in JavaScript, we have different approaches:
Method 1: Using return
In order to terminate a section of the script, a return statement can be included within that specific scope.
Example: Here, we are using return statement.
javascript
let i = 10;
// Return statement is in
// the global scope
if (i === 10)
return;let i = 10;
// Return statement is in
// the global scope
if (i === 10)
return;
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
document.write('This section will not be executed');
document.write('<br>');
document.write(arr.filter(
(elem, index) => { return elem > 2 }));
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
document.write('This section will not be executed');
document.write('<br>');
document.write(arr.filter(
(elem, index) => { return elem > 2 }));
Output:
In the absence of the return statement:
This section will not be executed
3, 4, 5, 6, 7, 8, 9
In the presence of return:
No output will be shown since the program is terminated on the encounter.
Method 2: Terminating a part of the Script
Example: Depending on a condition, a certain section of the script can be terminated using a "return" statement. The "return " statement returns "undefined" to the immediate parent scope, where the termination can be handled. This is the best practice since handling terminations makes it easier for future debugging and readability of the code.Â
javascript
function doSomeThing() {
let i = 10;
if (i === 10)
return;
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(
'This section will not be executed');
console.log(arr.filter(
(elem, index) => { return elem > 2 }));
}
let i = doSomeThing();
if (i === undefined)
console.log('Terminated');
Output:
Terminated
Method 3: Throwing an error on purpose
Example: We deliberately throw an error to terminate the section of the script that we want to. It is best practice to handle the error using a "try-catch" block.Â
javascript
function doSomeThing() {
let i = 10;
if (i === 10)
throw new Error(
'Program Terminated');
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(
'this section will not be executed');
console.log(arr.filter(
(elem, index) => { return elem > 2 }));
}
try {
doSomeThing();
}
catch (err) {
console.log(err.message);
}
Output:
Program Terminated
Method 4: Using process.exit for Node.JS applications
Example: There will be no other output, in this case since we exited the script. This is applicable to all JavaScript applications in the NodeJS environment. There are numerous other methods such as process.kill(process.pid) and process.abort() in NodeJS but process.exit() suffices for most of the cases, if not all cases.
javascript
function doSomeThing() {
let i = 10;
console.log('Terminating ');
process.exit(0);
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(
'This section will not be executed');
console.log(arr.filter(
(elem, index) => { return elem > 2 }));
}
doSomeThing();
Output:
Terminating:
Method 5: Using clearInterval() method
The clearInterval() function in javascript clears the interval which has been set by the setInterval() function before that.
Syntax:
clearInterval(nameOfInterval);
Example: Here, Clicking the "Start Script" button initiates a repeating action every second using setInterval()
. Clicking the "Stop Script" button stops the repeating action by calling clearInterval(intervalId)
, where intervalId
is the ID returned by setInterval()
. The script logs "Repeating action..." to the console every second until you click "Stop Script," at which point it logs "Script stopped."
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Script Termination Example</title>
</head>
<body>
<button id="startButton">Start Script</button>
<button id="stopButton">Stop Script</button>
<script>
let intervalId; // Variable to store the interval ID
function repeatingAction() {
console.log("Repeating action...");
}
document.getElementById("startButton")
.addEventListener("click", function () {
// Start the repeating action every 1 second
intervalId = setInterval(repeatingAction, 1000);
});
document.getElementById("stopButton")
.addEventListener("click", function () {
// Stop the repeating action when the "Stop Script"
// button is clicked
clearInterval(intervalId);
console.log("Script stopped.");
});
</script>
</body>
</html>
Output:

Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read