JavaScript - robbiehume/CS-Notes GitHub Wiki
Related Wiki links
Useful links
- Different ways to loop through array in JS
- JS vs jQuery vs Ajax
- JavaScript Overview (MDN)
- Complete JavaScript handbook (free codecamp)
Useful sites
Look into:
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) whilelet
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:
- Browser API/Web API events or functions: these include methods like
setTimeout
, or event handlers like click, mouse over, scroll, and many more - Promises: unique JavaScript object that allows us to perform asynchronous operations
- Browser API/Web API events or functions: these include methods like
- Browser APIs like
setTimeout
and event handlers rely oncallback
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 thejob queue
- Items in the
job queue
are given priority over thecallback 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 anexecutor
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
andreject
methods, respectively
- You can do that by calling the
- 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()
methodpromise.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 thejob 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 thecallback 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 amicro task
await
await
is usually used to unwrap promises by passing aPromise
as the expression- Using
await
pauses the execution of its surroundingasync
function until the promise is settled (that is, fulfilled or rejected)
jQuery
- jQuery Examples
- The standalone $ stands for jQuery. Ex:
$.each()
is equivalent tojQuery.each()
- Side note:
$.each()
is not the same as$(selector).each()
; source
- Side note:
- 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
- Ex.
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
- Looping through array: link (forEach, for(i in arr), for(x of arr), etc.)
.filter()
/.map()
/.reduce()
.forEach()
: link.some()
/.every()
/.find()
: linksome()
/every()
is equivalent toany()
/all()
in Pythonfind()
is the same syntax assome()
/every()
, except instead of a boolean it returns the object
localStorage
- Can use localStorage to persist data in the browser. Useful instead of cookies because they last longer