Udemy logo

JavaScript exitIf you are new to web programming, coming from a procedural language like C, or C++ or even Java, it is a lot of new ideas and concepts. One of the most important things to ask about in your code in a procedural program is when to exit or stop the routine and return to the host processing system.

In web programming, there is a separation between the client-side and the server-side code. We will mostly focus on the latter – JavaScript. Various languages, including JavaScript, the new Dart-lang from Google, and earlier VB Script from Microsoft, are supported in the web browser to enhance user experience by programming the HTML pages on the client-side browsers.

This blog post focuses on the challenges of client-side programming when you have to abort or exit processing events, or exit from your JavaScript code. The challenge, to someone from a procedural background, is the non-availability of the usual routines like exit(), abort(). Read on about client-side programming and challenges of writing code that exits early from processing.

Basic Exit

Client-side programming involves writing JavaScript code that runs in tandem with the browser under the following limitations,

  1. main-thread of execution of the program belongs to the browser

  2. JavaScript is invoked on demand; JavaScript code does not control the browser

  3. JavaScript code cannot write to a file on disk

  4. JavaScript code cannot exit the main thread of control or the browser.

So what does this mean for you to write code like ‘exit’ in the user thread? You will have to seek alternate strategies. Read on.

Client-Side JavaScript Operations

JavaScript does allow you to do the following operations on a browser window,

  1. Early return from functions

  2. Close a new window opened by JavaScript

  3. Change location of current window in JavaScript

In this blog post we shall illustrate 1, and 2. Action 3 is controlle by changing the property ‘location’ of the ‘window’ object, and is easily demonstrated in a similar fashion.

Server-Side : Exit in Node.js

However, server-side JavaScript with node.js is another story. There is some respite, on the server-side. JavaScript starts resembling a more traditional programming language. It provides an exit method on the process object. In the following code listing,

var i = 0;

for( i = 0; i < 10; i++ ) {

 console.log('value of i = '+i);

}

process.exit(55-i)//exit code = 45 

and running it on the terminal using the command you will see output as,

$ node node_exit.js



value of i = 0

value of i = 1

value of i = 2

value of i = 3

value of i = 4

value of i = 5

value of i = 6

value of i = 7

value of i = 8

value of i = 9



$ echo $?



45

which shows the exit code to be 45. With this brief detour into node.js we will stop discussing the exit() method in this article, as it pertains to the server-side JavaScript

Developing In JavaScript

You don’t need extra download for learning and running JavaScript to try these examples. They work on any browser like Google Chrome, Mozilla Firefox. For convenience of testing you can install the FireBug extension on Firefox, or use the existing Developer Tools in Chrome.

For node.js you need to install ‘node’ package, and ‘npm’ the node package manager.

Example – Stopping Your Function

In this example we will exit from a user written JavaScript code ,

<html>

<head>

<script src="./jquery.js"></script>

<script type="text/javascript">

var do_exit_early = function() {

     var i1 = 1;

     while( i1 < 100 ) {

        greet_user();

        console.log( i1 );

        if ( i1 == $("#widget").val() ) {

             return;

         }

         i1 = i1 + 1;

     }

};

function greet_user() {

  var value = '<div>Hello user! Your browser is <I>'+navigator.userAgent+"</I></div>";

  $("#data").html( $('#data').html() + value );

  console.log( value )

}

</script>

</head>

<body>

<input type="entry" id="widget" value=2> </input>

<input type="button" onClick="javascript:do_exit_early();" value="OK"> </input>

<div id="data">

</div>

</body>

</html>

and saving it as ‘early_exit.html‘ you should see expected behavior on clicking the buttons in your Chrome browser. The number you enter in the widget before clikcing the button controls the number of times the function ‘greet_user’ is invoked.

Using the default level there should be also the following output in the console,

<div>Hello user! Your browser is <I>Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36</I></div> early_exit.html:20

1early_exit.html:9

<div>Hello user! Your browser is <I>Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36</I></div> early_exit.html:20

2early_exit.html:9

<div>Hello user! Your browser is <I>Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36</I></div> early_exit.html:20

3

Example – Closing a New Window

In this example we will use JavaScript to close a window opened by the code in HTML page, based on user actions. This happens according to the following user events,

  1. User clicks ‘launch’, the new window is launched with MSN website as the target URL.
  2. User clicks ‘close’, we close the new window, keeping the original window.
  3. All these functions are achieved programmatically using the client-side JavaScript.Putting it all together we get the HTML + JavaScript code, and saving it as ‘close_demo.html’ you should see expected behavior on clicking the buttons in your Chrome browser.
<html>

<head>

<script src="./jquery.js"></script>

<script type="text/javascript">

var init = function() {

   console.log("Init fcn");

};

var windowID;

function close_window() {

  if ( windowID ) {

       windowID.close();

       windowID = null;

  }

};

function launch_window( ) {

   //ensure popups are allowed by your browser

   windowID = window.open("http://google.com","blank","width=260px","height=250px");

};

</script>

</head>

<body onload="init();">

<button onclick="javascript:launch_window();">Launch</button><BR />

<button onclick="javascript:close_window();">Close</button><BR />

</body>

</html>

which you can run on the Google Chrome browser, click the ‘Launch’ button on the form, and see the new popup window loading Google website. Also clicking the ‘Close’ button exits the new Google window.

Summary

Since the browser and JavaScript engine have to run simultaneously, your options are limited on client-side JavaScript. You can however overcome the challenges in creative ways. Server-side JavaScript offers more options, as increasingly used in the backend via Node.js and other platforms.

Page Last Updated: April 2014

JavaScript students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo