NEW Way To Create Variables In JavaScript

Web Dev Simplified · Beginner ·💻 AI-Assisted Coding ·2y ago

Key Takeaways

The video discusses the new `using` keyword in JavaScript for creating variables that can automatically handle cleanup processes, and demonstrates its usage with libraries like the file system library.

Full Transcript

JavaScript just added a brand new keyword called using for creating a variable that can replace let and const for specific scenarios and it's really great for those scenarios but there are a few things that they did with this which are really weird in this video I'm going to show you what that using keyword is as well as explain some of the really weird stuff they did that I don't really think is a good idea [Music] welcome back to web dev simplified my name is Kyle and my job is to simplify the web for you so you can start building your dream project sooner and in order to even understand the using keyword we first need to figure out what code it is trying to solve so if we look at our code right here you can see we have this write file function which takes in a path for a file we want to write to you can see it's going to open up that file with the read permission and the write permission we're going to be writing some random text to that file and then we're going to make sure we close out of that file so they don't have any open handlers to our file because if we open a bunch of files and never close those handles that's a problem because now no other part of a program on our computer can access those files because they're currently being accessed by this function right here so it's really important to make sure you close your files whenever you access them and if we look over here inside this files folder you can see we created a file with that text right there and if I were to change this to say something else for example and I give this a save you can now see that it says something else inside of that file so at least we know that this code is working the problem comes like let's say we want to add to this code where if we have a temp file we want to do something different than if we don't so what's coming here we'll create new 2 we'll call onetep.txt and we'll call 1a.txt and we'll check here to see if the path includes the type text inside of it I'm sorry temp if we know that this is a temp file well I just want to return I don't want to do anything else then what we can do is down here we can actually write some more information to this file so we'll just say that we want to write into here the text of permanent because we know this is a permanent file and we're going to make sure that we do that on our file there we go now I'm going to save this I'm going to go ahead and look and you can see that this says text in permanent and our temp file does not say permanent you may think that this is working just fine but there's actually a huge problem with the way this program works if we go ahead and we look at our code a little bit closer to see exactly what's going on I'll even minimize this down here because we don't really need to have this open you'll see that it first opens up our file it writes to our file and then if it's a temp file it's returning which means it's never getting to the point where it's actually closing our file so if we want to make this actually work we need to move this close code up into here so it's duplicated in these two places and this is a really easy bug to fall into because you know we didn't really think about this whole closing thing we we just thought we need to return early so if you have a bunch of scenarios where you're returning earlier doing other different things you have to copy around this closing code everywhere and like let's say there's an error inside of our code like I just type something in wrong here like this this throws an error now we're never reaching the point where we're closing our files so we now need to wrap everything inside of a try catch to make sure we handle all that properly and overall it gets quite complicated how we need to actually do everything inside of here so instead there's this new using keyword that essentially takes care of all of this cleanup process for you automatically so the way that this using keyword works is instead of using const here I would actually use the word using and this using keyword just says I'm going to be using this file and what happens is once this file becomes out of scope so I no longer have access to this variable and it's being cleaned up by the garbage collector then what it's going to do is it's going to do all the closing and cleanup for example closing my file for me now in order to make sure all this syncs up properly you need to make sure a variable you're using actually is configured in the right format so let's go ahead and we'll create a function for actually opening a file Force so we can do all that extra configure behind the scenes the one nice thing though is in the future when this using keyword becomes more widespread because right now it's extremely experimental and not supported anywhere is that certain libraries like this file system Library will just support this natively for you so you don't have to worry about doing it yourself so what we can do is we can create a brand new file let's just come into here and we'll call this open file.ts and we'll just export from here a function called open file and I'm pretty much just going to copy over exactly what we have here so I want to create a brand new file just like that and we'll say const file is going to be equal to that let's make sure we import that FS Library there we go and then we also need to make sure we get the path in here like this there we go so now we have a file that we're creating and we could just come down here and return this file but that doesn't allow us to do this cleanup instead in order to do this automatic cleanup you need to return either a class or a function and that needs to have a specific property defined on it so we're just going to return a function to show you the easiest most simple version of this this function will have the Handler for our file so we'll just call this handle and we'll set it to our file it doesn't really matter what you call this this is just the normal thing we want to return the important part though is we also need to specify a symbol on here so we're going to use the symbol property to define a symbol and in the future when this is actually supported there will be a disposed property on our symbol so we can just say symbol.dispose like this and that is going to actually work but right now we obviously don't have access to this disposed property because it's experimental so one thing that we can do is we can just polyfill it so what I can do is I already have the polyfill written out so I'm just going to copy the code directly from this polyfill I'm just going to paste it into here we can put this wherever we want but in our case we just need to make sure that we have this symbol.disposed actually doing something for us that's all that really matters this will be implemented in the browsers as soon as it's actually available then if we just make sure we ignore any typescript errors again because this is something that's not part of the browser yet we can Define this as a function so we can come in here to find this as a function and now whenever my file is essentially no longer in scope anymore it'll call this function and automatically do cleanup for me so to prove that I'm just going to console log inside of here dispose so we can know when this function is being called and then what I can do is I can actually close this file synchronously so I'll say close sync of our file just like that now if I give that a save I can go back into our script and I can import that open file function just like that and then I can use that here instead of the other way that I was opening my file and now it's giving me this file and if I hover over this file you can see that it has this weird thing right here this is just the symbol Pretend This doesn't exist in the future it wouldn't actually show up and then we have this handle right here so instead of using our file we just want to use the handle portion of our file because it's actually going to get us the actual file itself and now everywhere we were closing our file we no longer need that code so now if I give that a quick save and I make sure I pass in just my path here and nothing else you should notice that in my console you can see it says dispose twice that means that it's actually cleaning up my files because what's happening is I'm saying I want to use this file and by saying that I know that this file should have a symbol on it with the text of dispose it's a dispose symbol so with that in mind I use this file exactly the same as normal but using knows that there's a special function I have defined on here and that function gets called immediately as soon as this file is no longer in scope so it goes throughout this function file still here file still used and as soon as we either call return or get to the end of this function well this file is no longer usable anywhere else because it's only usable in in the function so when we leave the function it obviously leaves scope so what happens is Javascript is smart enough to go okay this file no longer exists let's clean this up by calling the dispose function it's logging out dispose and then it's making sure it closes the actual reference to that file so it can be used by other parts of our program this is really important like if you're doing a database connection or you're doing like a websocket connection anything where you're making these connections that you need to make sure you close or disconnect from this is a really clean and easy way to handle that I actually really like that this is coming to JavaScript so really kind of show you exactly what's going on with this what I'm going to do is I'm just going to create a bunch of different files that I open so I'm just going to kind of remove all the code that we have here and instead I'm just going to call open file I'm just going to pass it in some different numbers so we'll just do like a for example and we'll say that this is using a is equal to that I'll just do this a couple times so I'll have like b c and d and I'll make sure that these all open different files so we'll say d c and b just like that but importantly I'm actually going to put C and D inside of their own scope by using brackets like this I'm just defining the scope which means I can only access C and D From Within These brackets if I were to try to like access C down here you'll notice that this variable doesn't exist and it'll even tell me you know like there's an error there's no C down here but if I use C inside of here obviously it works because it's within that scope and let's do this one more time for good measure we'll come down here with e we'll say e and e and what I'm going to do is I'm actually going to come into open file and I'm just going to change around our console logs so I'm going to say console.log I'm going to say plus and then I'm just going to put the actual name of the thing so we'll say here our path and then I'm going down here use a minus to essentially say that we're cleaning this up we can kind of see what's happening we have the pluses and the minuses if I expand up this output here and I just resave this you'll see that what's happening is first we are creating our file a b c and then D that makes sense we're using a we're using B we're using C we're using D then after we're done using D you can see we get to the bottom of this scope which now means that C and D are no longer available in our program because they are outside of their scope so we need to do our cleanup process so now you can see it's removing d and it's removing C okay now we're on this line right here where we create e so now you can see we're creating e and then finally we're at the end of our program which means we're outside of all of our different scope so we're cleaning up e b and a so you can kind of see how this is working as soon as a variable is no longer accessible it's outside of its scope it just completely removes it by calling this cleanup function which we have called dispose here now let's imagine we're in a scenario where we have an error inside of our code like let's say right here in between C and D we just throw a new error this could be for any reason but our code is airing out for some reason normally this is a really hard thing to make sure all your different file handles are closed properly but with this using function method it's automatically handled for us when I save you can see we're getting an error but if we look at the output we're creating a b and c that's fine and then we get to this error this error gets thrown and the code goes oh crap we need to clean everything up so it removes c b and a so it automatically handles all the closing in any scenario you could ever run into this part of using I absolutely love but the part I don't love is what happens if you have asynchronous code so if we go back to open file we can obviously close our file with without doing it synchronously and we can do it asynchronously as well so we would need to like await this for example and this is asynchronous code to do that we need to use an asynchronous dispose method and luckily there's actually one that's built in so we can just say instead of dispose we'll say async dispose and we'll say that this is an asynchronous function just like that by doing this we're essentially saying that we want to clean this up asynchronously by using async await super straightforward and simple stuff but obviously the way we handle this is going to be a little bit different because if I just save and make sure this error is no longer here things aren't going to work as we expect them to because we're not making sure that we handle these asynchronously so the way that we get around this with JavaScript is if we want to open something up asynchronously we need to put the await keyword in front of using so if I just put this inside of a function we can actually use the await keyword and I make this in async function and then I'll just call it down here there we go what I need to do is I just need to prefix all of these usings with the weight keyword and now it's going to work as I expect you can see a b c d then we clean up D and C create e and then clean up the last three that we have left now the reason I don't like this if we look at the code is the await keyword here doesn't actually wait at all it's just saying that when we get to the end of the scope then we're going to do some awaiting and you'll notice this because I can come into here and I can just say like here now if I look at the actual output give this a save again you'll see it says it's creating a and then we're printing out here and then it's creating b c d there's no actual awaiting going on in this specific scenario the awaiting happens when we clean up a all the way down here at the very bottom so I don't really like the way that they use this await keyword here because they're using the same exact keyword you use for awaiting promises which waits in line which means all of this code must actually wait for this code up here but really what this await keyword is saying is when we get to the very end of the scope where a is being used then we want to do our weighting we don't want to do it until all the way way at the very end so it's a little bit confusing in my opinion why they use this weight keyword here I really wish they would change this but that's what it is right now and it seems like that's what it's going to be when they actually implement this in the real JavaScript language other than that though I really like that this new keyword is being added especially as it starts to get added into the actual features built into the browsers and into node because it'll make working with things like files and so on so much easier now if you enjoyed that and want to Dive Into The Cutting Edge of JavaScript I'm going to have some other Cutting Edge features linked right over here for you to check out with that said thank you very much for watching and have a good day

Original Description

The brand new using keyword is yet another way to declare variables in JavaScript. This using keyword is pretty niche in how it should be used but when it is fully implemented into libraries it will make handling closing connections and cleanup tasks so much easier. 🌎 Find Me Here: My Blog: https://blog.webdevsimplified.com My Courses: https://courses.webdevsimplified.com Patreon: https://www.patreon.com/WebDevSimplified Twitter: https://twitter.com/DevSimplified Discord: https://discord.gg/7StTjnR GitHub: https://github.com/WebDevSimplified CodePen: https://codepen.io/WebDevSimplified ⏱️ Timestamps: 00:00 - Introduction 00:30 - Problematic Code Example 02:50 - Using Keyword Basics 09:41 - Async Using #JSUsing #WDS #JavaScript
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Web Dev Simplified · Web Dev Simplified · 0 of 60

← Previous Next →
1 Introduction to Web Development || Setup || Part 1
Introduction to Web Development || Setup || Part 1
Web Dev Simplified
2 Introduction to Web Development || Understanding the Web || Part 2
Introduction to Web Development || Understanding the Web || Part 2
Web Dev Simplified
3 Introduction to HTML || Your First Web Page || Part 1
Introduction to HTML || Your First Web Page || Part 1
Web Dev Simplified
4 Introduction to HTML || Basic HTML Elements || Part 2
Introduction to HTML || Basic HTML Elements || Part 2
Web Dev Simplified
5 Introduction to HTML || Advanced HTML Elements || Part 3
Introduction to HTML || Advanced HTML Elements || Part 3
Web Dev Simplified
6 Introduction to HTML || Links and Inputs || Part 4
Introduction to HTML || Links and Inputs || Part 4
Web Dev Simplified
7 Learn Git in 20 Minutes
Learn Git in 20 Minutes
Web Dev Simplified
8 5 Must Know Sites For Web Developers
5 Must Know Sites For Web Developers
Web Dev Simplified
9 10 Best Visual Studio Code Extensions
10 Best Visual Studio Code Extensions
Web Dev Simplified
10 Learn CSS in 20 Minutes
Learn CSS in 20 Minutes
Web Dev Simplified
11 How to Style a Modern Website (Part One)
How to Style a Modern Website (Part One)
Web Dev Simplified
12 How to Style a Modern Website (Part Two)
How to Style a Modern Website (Part Two)
Web Dev Simplified
13 3D Flip Button Tutorial
3D Flip Button Tutorial
Web Dev Simplified
14 How to Style a Modern Website (Part Three)
How to Style a Modern Website (Part Three)
Web Dev Simplified
15 Animated Loading Spinner Tutorial
Animated Loading Spinner Tutorial
Web Dev Simplified
16 How to Write the Perfect Developer Resume
How to Write the Perfect Developer Resume
Web Dev Simplified
17 Animated Text Reveal Tutorial
Animated Text Reveal Tutorial
Web Dev Simplified
18 Learn Flexbox in 15 Minutes
Learn Flexbox in 15 Minutes
Web Dev Simplified
19 Custom Checkbox Tutorial
Custom Checkbox Tutorial
Web Dev Simplified
20 Start Contributing to Open Source (Hacktoberfest)
Start Contributing to Open Source (Hacktoberfest)
Web Dev Simplified
21 JavaScript Shopping Cart Tutorial for Beginners
JavaScript Shopping Cart Tutorial for Beginners
Web Dev Simplified
22 Responsive Video Background Tutorial
Responsive Video Background Tutorial
Web Dev Simplified
23 1,000 Subscriber Giveaway
1,000 Subscriber Giveaway
Web Dev Simplified
24 How To Prevent The Most Common Cross Site Scripting Attack
How To Prevent The Most Common Cross Site Scripting Attack
Web Dev Simplified
25 Transparent Login Form Tutorial
Transparent Login Form Tutorial
Web Dev Simplified
26 The Forgotten CSS Position
The Forgotten CSS Position
Web Dev Simplified
27 How to Code a Card Matching Game
How to Code a Card Matching Game
Web Dev Simplified
28 10 Must Install Visual Studio Code Extensions
10 Must Install Visual Studio Code Extensions
Web Dev Simplified
29 Learn CSS Grid in 20 Minutes
Learn CSS Grid in 20 Minutes
Web Dev Simplified
30 Learn JSON in 10 Minutes
Learn JSON in 10 Minutes
Web Dev Simplified
31 10 Essential Keyboard Shortcuts For Programmers
10 Essential Keyboard Shortcuts For Programmers
Web Dev Simplified
32 What Is The Fastest Way To Load JavaScript
What Is The Fastest Way To Load JavaScript
Web Dev Simplified
33 Differences Between Var, Let, and Const
Differences Between Var, Let, and Const
Web Dev Simplified
34 How To Install MySQL (Server and Workbench)
How To Install MySQL (Server and Workbench)
Web Dev Simplified
35 Learn SQL In 60 Minutes
Learn SQL In 60 Minutes
Web Dev Simplified
36 How To Solve SQL Problems
How To Solve SQL Problems
Web Dev Simplified
37 What Are Design Patterns?
What Are Design Patterns?
Web Dev Simplified
38 Null Object Pattern - Design Patterns
Null Object Pattern - Design Patterns
Web Dev Simplified
39 Your First Node.js Web Server
Your First Node.js Web Server
Web Dev Simplified
40 How To Setup Payments With Node.js And Stripe
How To Setup Payments With Node.js And Stripe
Web Dev Simplified
41 How To Learn Any New Programming Skill Fast
How To Learn Any New Programming Skill Fast
Web Dev Simplified
42 Asynchronous Vs Synchronous Programming
Asynchronous Vs Synchronous Programming
Web Dev Simplified
43 JavaScript ES6 Arrow Functions Tutorial
JavaScript ES6 Arrow Functions Tutorial
Web Dev Simplified
44 Are You Too Old To Learn Programming?
Are You Too Old To Learn Programming?
Web Dev Simplified
45 JavaScript Cookies vs Local Storage vs Session Storage
JavaScript Cookies vs Local Storage vs Session Storage
Web Dev Simplified
46 JavaScript Promises In 10 Minutes
JavaScript Promises In 10 Minutes
Web Dev Simplified
47 Builder Pattern - Design Patterns
Builder Pattern - Design Patterns
Web Dev Simplified
48 JavaScript == VS ===
JavaScript == VS ===
Web Dev Simplified
49 JavaScript ES6 Modules
JavaScript ES6 Modules
Web Dev Simplified
50 8 Must Know JavaScript Array Methods
8 Must Know JavaScript Array Methods
Web Dev Simplified
51 CSS Variables Tutorial
CSS Variables Tutorial
Web Dev Simplified
52 JavaScript Async Await
JavaScript Async Await
Web Dev Simplified
53 How To Choose Your First Programming Language
How To Choose Your First Programming Language
Web Dev Simplified
54 Easiest Way To Work With Web Fonts
Easiest Way To Work With Web Fonts
Web Dev Simplified
55 Singleton Pattern - Design Patterns
Singleton Pattern - Design Patterns
Web Dev Simplified
56 Responsive Navbar Tutorial
Responsive Navbar Tutorial
Web Dev Simplified
57 CSS Progress Bar Tutorial
CSS Progress Bar Tutorial
Web Dev Simplified
58 Learn GraphQL In 40 Minutes
Learn GraphQL In 40 Minutes
Web Dev Simplified
59 What is an API?
What is an API?
Web Dev Simplified
60 Learn How To Build A Website In 1 Hour!
Learn How To Build A Website In 1 Hour!
Web Dev Simplified

The video teaches how to use the new `using` keyword in JavaScript to create variables that can automatically handle cleanup processes, making code more readable and maintainable. The `using` keyword can simplify working with files and other features in browsers and Node.

Key Takeaways
  1. Create a new file with the `using` keyword
  2. Use the `using` keyword to create a variable that can handle cleanup processes
  3. Move cleanup code to a separate block using the `using` keyword
  4. Wrap code in a try-catch block to handle errors
  5. Create a custom `dispose` function to clean up files when they go out of scope
  6. Use the `using` function to automatically handle cleanup of resources
💡 The `using` keyword can automatically handle cleanup processes, making code more readable and maintainable

Related Reads

📰
The AI That Out-Forecasted Europe’s Best Supercomputers-Using a Single Chip
Learn how a single chip AI outperformed Europe's best supercomputers in weather forecasting, and why this matters for the future of AI and computing
Medium · AI
📰
Day 4 of 100 Days of GenAI for DevOps🚀
Learn what ChatGPT stands for and its significance in conversational AI, enabling you to better understand AI-powered tools in DevOps
Dev.to AI
📰
Local LLMs for agentic coding: a real-world viability report
Learn how local LLMs perform in real-world agentic coding tasks, including file reads and writes, and understand their viability
Dev.to AI
📰
Beyond Replication: Theo Browne on AI's 'Skeuomorphic Phase' and the Future of Development
Learn about AI's 'Skeuomorphic Phase' and its implications on the future of development with Theo Browne's insights
Dev.to AI

Chapters (4)

Introduction
0:30 Problematic Code Example
2:50 Using Keyword Basics
9:41 Async Using
Up next
Connect Claude AI to Canva & Create Stunning Designs in Minutes! Claude Ai Use case
Quick Tips - Web Desiign & Ai Tools
Watch →