JavaScript - robbiehume/CS-Notes GitHub Wiki

JavaScript Colab Notes

Related Wiki links

Useful links

Useful sites

Look into:

  • Prototypes / classes: link
  • OOP: link
  • Promises
  • let vs var

General notes

let vs var: link

  • Other link showing loop use case
  • The main difference is scoping rules. Variables declared by var keyword are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } (hence the block scope)

Asynchronous

Overview

  • Synchronous vs Asynchronous JavaScript – Call Stack, Promises, and More
  • JavaScript is synchronous by default, but it is possible to asynchronous tasks
  • We can classify most asynchronous JavaScript operations with two primary triggers:
    1. Browser API/Web API events or functions: these include methods like setTimeout, or event handlers like click, mouse over, scroll, and many more
    2. Promises: unique JavaScript object that allows us to perform asynchronous operations
  • Browser APIs like setTimeout and event handlers rely on callback functions. A callback function executes when an asynchronous operation completes
  • The event loop manages the call stack and receives browser APIs / callback function calls
  • There is also a special callback queue / task queue that holds tasks to run once the call stack is empty
  • For promises, the JavaScript engine doesn't use the callback queue; it uses another special queue called the job queue
  • Items in the job queue are given priority over the callback queue items
  • Order of precedence (first to last): call stack, promises, browser APIs (async callbacks)

Promises

  • Guide to JS promises (free code camp)
  • In JavaScript, promises are special objects that help you perform asynchronous operations
  • You can create a promise using the Promise constructor, which takes an executor function
  • In the executor function, you define what you want to do when a promise returns successfully or when it throws an error
    • You can do that by calling the resolve and reject methods, respectively
  • Example: const promise = new Promise((resolve, reject) => resolve('I am a resolved promise'))
  • After the promise is executed, we can handle the result using the .then() method and any errors with the .catch() method
    • promise.then(result => console.log(result))
  • For promises, the JavaScript engine doesn't use the same callback queue we have seen earlier for browser APIs. It uses another special queue called the job queue

Job Queue

  • Every time a promise occurs in the code, the executor function gets into the job queue
  • The event loop works, as usual, to look into the queues but gives priority to the job queue items over the callback queue items when the stack is free
  • The item in the callback queue is called a macro task, whereas the item in the job queue is called a micro task

await

  • await is usually used to unwrap promises by passing a Promise as the expression
  • Using await pauses the execution of its surrounding async function until the promise is settled (that is, fulfilled or rejected)

jQuery

  • jQuery Examples
  • The standalone $ stands for jQuery. Ex: $.each() is equivalent to jQuery.each()
    • Side note: $.each() is not the same as $(selector).each(); source
  • There is also the $() method used to get HTML elements
    • $("p") : get all <p> elements
    • $("#test") : get all elements with id="test"
    • $(".test") : get all elements with class="test"
    • $(this) : get the current HTML element

Angular vs React vs Vue

Syntax Notes

  • || operator in variable definition: link
    • Ex. z = x || y: z will be set to x if x is 'truthy', otherwise it will be set to the value of y

Specific scenarios

  • Get difference between two arrays: link
  • Slice an array: arr.slice(start_index, end_index); ex: arr.slice(0,3); The last index is non-inclusive
  • Find certain values of an array: link
  • Sleep function:
    function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }
    sleep(1000).then(() => console.log('sleep'))
    
  • Adding clear button for input field: link; link2
  • Keep footer where it belongs: link
  • Get certain key value from list of JSON objects: 'cats.map((c) => c.name)` // get a list of all the names of cats

Arrays & array methods

localStorage

  • Can use localStorage to persist data in the browser. Useful instead of cookies because they last longer