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
How to terminate a script in JavaScript ?
To terminate a script in JavaScript, we have different approaches:
Table of Content
- Using return
- Terminating a part of the Script
- Throwing an error on purpose
- Using process.exit for Node.JS applications
- Using clearInterval() method
Contact Us