javascriptwebusing

Javascript Using Keyword

Learn how the new javascript using keyword works and its uses cases.
2/7/2024
7 minutes

Javascript 'using' keyword

At the start we had only 3 javascript keywords for declaring variables

  • var, enables you to declare a global variable from anywhere and overwrite it at any time, can be buggy if not used properly.
  • const and let, they both let you declare local variables, they came after and solved the problems the var keyword had.

Now we have a new javascript keyword for declaring varibles which is using.

The main usecase of this new keyword is for ressources, connections or anything that need to be cleaned up or closed.

For example

/**
 * let's assume we have access to 2 functions
 * open(filepath: string): File; it'll open a file and return an object to manipulate it
 * close(file: File): void; takes a File object and free it
 * **/

// using those two functions we would do something like this to handle a file

// Open the file
const file = open('./myfile.txt');

file.read();

// Close and free the file
close('./myfile.txt')

Now with the new using keyword you'll no more need to close your ressources after using them, it'll be done automatically. Take a look at the example below:

// Using the two functions we have, we have created this function that'll automatically handle file closing for us
const useFile = (filepath) => {
    return {
        [Symbol.dispose]: () => {
            close(filepath);
            console.log("file closed.")
        },
        file: open(filepath),
    }
}

using { file } = useFile('./myfile.txt')

file.read();

// don't worry about closing it, it'll be automatically closed when the variable is out of scope.
© Raideno.