Joe's
Digital Garden

Javascript

Front-End Frameworks

Ongoing research into [[Javascript Front-End Frameworks]], how they work, and how best to incorporate them into my own development practices.

Var vs Let vs Const

Sourced from "The Difference of "var" vs "let" vs" const" in Javacript by Megan Lo.

var
Scoped globally and locally. Can declare outside of a function and then use inside of that function.
We can also redeclare a var. That is, we can declare it in a function to overwrite the globally scoped var.
We can update the var variable to a new value.
let
Block-scoped. Can only be declared inside of a block.
Can be updated, but not redeclared in the same scope
const
Block-scoped. Cannot be redeclared.
Cannot be updated.

Best practice is to stick with let and use const if the variable will not be updated.

Async

Summarizing the Osberg's tutorial on async Javacript.

Also see: How to Use the Javascript Fetch API to Get Data.

  • Non-blocking function calls
  • Javacript in the browser uses an event loop to handle async calls
  • The browser places async work into two queues: microtask and macrotask
  • Promises are placed int othe microtask queue
  • Synchronous code runs first. Event loops after.
  • Promises represent a future value. Either the result of the function call or an error object. They have four possible states, fulfilled, rejected, pending, or settled.

Example promise:

const promise = new Promise((resolve, rject) => {
    if (response.status === 200) {
        resolve(response.body);
    } else {
        const error = {};
        reject(error);
    }
});

promise.then(res => {
    console.log(res);
}).catch(err => {
    console.log(err);
});

The resolve and reject closures are run on success (.then) or failure (.catch).

Async/Await is used to handle an asynchronous function call synchronously.

Example:

const getData = async () => {
    const response = await fetch('https://google.com');
    const data = await response.json()
    console.log(data)
}

getData();

External References

  1. Lo, Megan. The Difference of “var” vs “let” vs “const” in Javascript, The Startup. Retrieved 2021-03-16.
  2. Oseberg, Fredrik Strand. Async Await JavaScript Tutorial - How to Wait for a Function to Finish in Js, freeCodeCamp. Retrieved 2021-01-20.
  3. Ford, Ceora. How to Use the Javascript Fetch API to Get Data, DigitalOcean. Retrieved 2021-05-12.

Linked References