How to use return In Javascript
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.
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