Closures - Exercise

Welcome to our free Advanced JavaScript Programming tutorial. This tutorial is based on Webucator's Advanced JavaScript Programming course.

Contact Us or call 1-877-932-8228
Closures - Exercise


Duration: 15 to 25 minutes.

In the simple bank account application you will write in this exercise, you will use closures as a way to maintain state (to keep track of the account balance), to offer external code a way to get and set information (make a deposit or get the current balance), and to protect data (like the balance) from inappropriate tampering.

  1. Open AdvancedFunctions/Exercises/closures.html for editing.
  2. Write the body of function bankAccount as indicated in the comments:
    • Add local variables balance and ownerName
    • Return an object with fields for withdrawal(withdrawalAmount), deposit(depositAmount), getBalance(), and getOwnerName()
    • Add validation to ensure only appropriate withdrawals and deposits are allowed
  3. Test your solution in a browser.


<!DOCTYPE html>
	<meta charset="utf-8">
		function bankAccount(ownerName) {
			var balance = 0;
			var ownerName = ownerName;
			return {
				withdrawal: function(withdrawalAmount) {
					if (withdrawalAmount > 0 && withdrawalAmount <= balance) {
						balance -= withdrawalAmount;
				deposit: function(depositAmount) {
					if (depositAmount > 0) {
						balance += depositAmount;
				getBalance: function() {
					return balance;
				getOwnerName: function() {
					return ownerName;
		var myAccount = bankAccount('Jane Doe');
		document.write('Current balance: $' + myAccount.getBalance());
		document.write('<br>Current balance: $' + myAccount.getBalance());
		myAccount.withdrawal(2000); // this shouldn't work, since 2000 > current balance
		document.write('<br>Current balance: $' + myAccount.getBalance());
		myAccount.deposit(-2); // this shouldn't work, since -2 <= 0
		document.write('<br>Current balance: $' + myAccount.getBalance());
		document.write('<br>Account owner: ' + myAccount.getOwnerName());

Code Explanation

In function bankAccount we set local variables balance to 0 and ownerName to the string argument supplied when the function is first called.

Function bankAccount returns an object where each field is a function and thus a closure: this ensures that external code can get (myAccount.getBalance(), myAccount.getOwnerName()) and set (myAccount.deposit(100), myAccount.withdrawal(75)) properties, but external code cannot directly access nor modify properties.


This tutorial is based on Webucator's Advanced JavaScript Programming Course. We also offer many other JavaScript Training courses. Sign up today to get help from a live instructor.