To ensure a function call is performed later in a program’s execution, usually for purposes of cleanup, we can use constructs in JavaScript that mimic similar behavior. In JavaScript, a common pattern is to use finally blocks for cleanup.
Suppose we wanted to create a file, write to it, and then close it when we’re done. Here’s how we can achieve that in JavaScript using the fs module and finally for cleanup.
Below is the translated version of the Go code example into JavaScript.
It’s important to check for errors when closing a file, even in a deferred function. Running the program confirms that the file is closed after being written.
Now that we can run and build basic JavaScript programs, let’s learn more about the language.