Today, I learned about async and await and explored another concept related to closures in JavaScript.
As I continue learning JavaScript, Iām starting to understand how asynchronous operations work and how functions can remember variables from their surrounding scope.
1.Async and Await in Javascript
async and await helps us to work with promises and make synchronous code easier to understand
await pauses the execution of the surrounding async function until a Promise settles, allowing us to work with its result.
`async function greet() {
return "Hello, JavaScript!";
}
greet().then((result) => {
console.log(result);
});
`
Output:
Hello, JavaScript!
Example using await
`function getData() {
return new Promise((resolve) => {
resolve("Data received!");
});
}
async function displayData() {
let result = await getData();
console.log(result);
}
displayData();
`
Output:
Data received!
Here, await waits for the Promise to fulfill and assigns its result to the result variable.
2. Closures in JavaScript
A closure happens when a function remembers and can access variables from the scope where it was created, even after the outer function has finished executing.
Example
`function outerFunction() {
let message = "Hello from the outer function!";
function innerFunction() {
console.log(message);
}
return innerFunction;
}
let myFunction = outerFunction();
myFunction();`
Output:
Hello from the outer function!
In this example, innerFunction() can still access the message variable from outerFunction(). This is an example of a closure.
What I Learned Today
- How async and await work with Promises.
- How asynchronous functions return Promises.
- How await helps us work with Promise results.
- What a closure is and how a function can remember variables from its surrounding scope.
Top comments (1)
In other words, a closure is created EVERY time ANY function is created - nested or otherwise.