Scope - Exercise

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

Scope

Duration: 10 to 15 minutes.

In this exercise, you will fix some incorrect code by handling scope.

  1. Open Scope/Exercises/scope.html for editing.
  2. The purpose of function writeIt is to write the first numTimes multiples of multiple. For instance, writeIt(3, 2) should write 0 2 4 to the screen, since the first three multiples of 2 are 0 (that is, 0 x 2), 2 (1 x 2), and 4 (2 x 2). Similarly, writeIt(4, 3) should write 0 3 6 9, since the first four multiples of 3 are 0, 3, 6, and 9.
  3. The code does not, however, work as intended. Find and fix the error.
  4. Test your solution in a browser.

Solution:

Scope/Solutions/scope.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Scope: Functions inside Functions</title>
	<script>
		function writeIt(numTimes, multiple) {
		    function doMultiplication(val, multiple) {
		        var i = val * multiple;
		        return i;
		    }

		    for (var i=0; i<numTimes; i++) {
		        document.write(doMultiplication(i, multiple) + ' ');
		    }
		}
	</script>
</head>
<body>
	<h1>Scope Exercise</h1>
	<script>
		writeIt(5, 2);
	</script>
</body>
</html>

Code Explanation

Perhaps unsurprisingly, the error is related to scope: function doMultiplication uses a variable i which, in the absence of any var or let keyword, modifies the i variable in the for loop. One way to fix this is to use the var keyword in the declaration of variable i in function doMultiplication - this scopes i local to function doMultiplication and thus it does not modify the value of i in the for loop from the calling code. (Of course, one could make the case that function doMultiplication is not needed here for this simple purpose, but we offer this exercise as an example of how easy it is to run into scope issues with variables and functions.)

Solution:

Scope/Solutions/scope2.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Scope: Functions inside Functions</title>
	<script>
		function writeIt(numTimes, multiple) {
		    function doMultiplication(val, multiple) {
		        i = val * multiple;
		        return i;
		    }

		    for (let i=0; i<numTimes; i++) {
		        document.write(doMultiplication(i, multiple) + ' ');
		    }
		}
	</script>
</head>
<body>
	<h1>Scope Exercise</h1>
	<script>
		writeIt(5, 2);
	</script>
</body>
</html>

Code Explanation

In this second solution, we declare the for loop variable i with the let keyword. This scopes i to the nearest block - in this case, the for loop. This ensures that - even if we incorrectly left off the var keyword when declaring a same-named variable in function DoMultiplication - other variables would not modify the for loop variable.

Next