This is a more powerful version of Python’s
lambda. This feature is extremely common in the wild. A lot of what you need to do in the web requires asynchronous activity and callbacks upon completion. For example, if your web page makes a call in the background to get more data, you can’t block the browser waiting for a result. You give the calling mechanism a function that it should call when the result is obtained.
hello.js. This is a pretty simple function that takes a single argument. With the exception of some syntax differences, this is pretty close to Python. Instead of
def you use
function and instead of whitespace indentation you use curly brackets, but the idea is the same. In the lower area, I’m inside of a Node REPL session.
First off, note that I’ve run Node in the same directory as
hello.js. This is so that I didn’t have to fully qualify the filename. When a file is loaded, the REPL shows the contents on the screen and if anything was run. In this case, it’s just the declaration of the function in the file. As the file itself doesn’t return anything, you also get the ubiquitous
undefined as a report of the result of the
That’s all the stuff that you see on the screen after the call. I’m going to scroll back down now. Through the magic of video editing, let’s say now is when that 3 seconds has passed. And there you have it, the call to
say_hello(), but delayed.
In the top area, I’ve replaced
say_hello() with a new function called
future_message(). This function uses
setTimeout() inside of it on line 4. Notice here that instead of using a named callback, this time I’m using an anonymous function.
setTimeout() has access to the
message parameter in the parent function.
=>). In the top area, I’m going to replace
Note that the
count variable in the parent function is in scope of the anonymous function. After 4 instances, the inner anonymous function clears the interval on line 9, and then you’re done. Let’s see this in action. First, I’ll load the file,
Become a Member to join the conversation.