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
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