Skip to main content
Ben Nadel at CFCamp 2023 (Freising, Germany) with: Hanna Eckert
Ben Nadel at CFCamp 2023 (Freising, Germany) with: Hanna Eckert

Trying To Mimic LET Functionality In JavaScript Using Self-Executing Functions

By
Published in Comments (2)

Last night, I was listening to the Lately In JavaScript podcast. Among the many items discussed, one topic that was brought up was the emergence of the LET keyword in the next version of ECMAScript (the language on which JavaScript is based). LET allows for block-level variable binding; so, while the VAR keyword allows for function-level variable binding, LET allows variables to be defined for a smaller scope of code execution. LET-like functionality can be achieved through the use of closures; and, while I've talked about it before, when exploring closures, I thought it might be nice to demonstrate this as a stand-alone post.

As one of the earliest posts on my blog, way back in 2006, I talked about the problem with variable binding inside the context of loops. If you didn't understand variable hoisting (as I didn't at the time), configuring event handlers inside a FOR loop could quickly lead to unexpected and frustrating behaviors.

When I started using jQuery, shortly thereafter, I was super pumped-up to find out that the .each() method could alleviate some of these variable hoisting problems. By using a callback for each "loop iteration," jQuery's each() method bypassed the hoisting problem by providing each iteration with its own scope (and hoisting context).

This same sandboxing effect can be used outside of jQuery through the use of self-executing function expressions. Essentially, you can create an anonymous function within the block of a FOR loop; then, for each iteration, invoke the anonymous function, defining the relevant context and passing in the index values.

In the following demo, we'll define a number of methods that bind to the "current" value of "i." Then, we'll execute those methods after the loop to see if the iteration-specific value-binding took place.

<!DOCTYPE html>
<html>
<head>
	<title>Inline Functions Create Sandboxes For Variable Binding</title>
	<script type="text/javascript">


		// Create a buffer to hold our function - these will invoked
		// at the end to demonstrate variable binding.
		var methodBuffer = [];


		// We'll create 5 functions.
		for (var i = 0 ; i < 5 ; i++){

			// Create a "unexpected behavior" binding to i.
			var j = i;

			// Create an inline, self-executing function to create a
			// closure and sandbox for the execution of this loop
			// iteration.
			(function( i ){

				// Create our testing function - notice that the
				// console.log() method is referencing "i", which is
				// a variable defined by our self-executing function,
				// and the variable, "j", which is a variable defined
				// in the FOR loop block.
				var method = function(){
					console.log( i, "-", j );
				};

				// Add it to the buffer - we'll see if the binding
				// holds up afterward.
				methodBuffer.push( method );

			}).call( this, i );
			// Notice that when we invoke this inline function,
			// we're binding the execution context AND passing in
			// the current value of [i].

		}


		// Now, test the methods and the variable bindinds.
		while (methodBuffer.length){

			// Get the front method (changes the length of the array).
			var method = methodBuffer.shift();

			// Invoke it to see if the "console.log(i)" variable
			// binding is referencing the correct value.
			method();

		}


	</script>
</head>
<body>
	<!-- Left intentionally blank. -->
</body>
</html>

As you can see, we have a simple FOR loop iterating from zero to four. For each loop, we define and then invoke an anonymous function block. In order to maintain the proper execution context, we're using the call() method to explicitly set the "this" value used within the anonymous function. As part of the anonymous function invocation, we're also passing in i - the value of the loop iteration index. This creates an iteration sandbox while also binding the iteration index to the invocation parameter of the self-executing function.

As a control, we're also logging the value of, "j," which is bound to the value, "i," at the FOR-loop level. Since "j" is not being passed into the self-executing function, it will fall victim to the hoisting effect. And, in fact, when we run the above code, we get the following console output:

0 - 4
1 - 4
2 - 4
3 - 4
4 - 4

As you can see, each function definition was bound to the appropriate value of "i." And, the value of "j" was bound to the last known value of "i".

The LET keyword can do a bit more than what I described; but, the primary function of the LET keyword can be somewhat replicated through the use of self-executing function blocks. Since the self-executing function blocks are invoked for each iteration of our FOR loop, it provides both an execution sandbox and an opportunity to bind iteration variables to invocation arguments.

Want to use code from this post? Check out the license.

Reader Comments

1 Comments

Great post Ben, but I think that using

Function.prototype.call

may mislead readers, it isn't the key point in your post.

Moreover, the sentence "we're binding the execution context" isn't true. The "Execution Context" is defined in ES specification section 10.3 (see http://es5.github.com/#x10.3).

With

(function(i){ ... ).call( this, i )

you are binding the inner *this* and the *thisValue* of the enclosing lexical scope.

I think

(function(innerIndex){ ... ))(outerIndex)

is clearer for the point you're explaining.

15,902 Comments

@Joseanpg,

You make a really good point regarding the use of call(). I was, originally, gonna just invoke the function normally; but then, after it was written, I went back and added the call() usage. Probably did more to dilute than clarify.

On that topic, however, I think I heard that one of the things they are going to "fix" in the upcoming release of ECMAScript is the way the "this" scope works in function expressions. Don't quote me on this, but I think they are going to do what we all *hoped* it would do - keep the same this-binding as the defining context (unless called via call() or apply(), of course).

From that link you provided, it looks like "Execution context" is composed of a number of things. As you pointed out, I am referring to the "this" binding; but it looks like that is only *part* of the execution context:

- Lexical environment (ie. closure'd variabled)
- Variable environment (ie. variable defs)
- This binding (ie. what "this" refers to).

That's a much better definition than what I had in my head. With all the scope chain stuff and stacks, I never really knew what to call it. Thanks for helping me get my mind straight!

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel