Javascript
The DOM
document
(web page). Provides properties and functions for developers to use to manipulate the web pagedocument.getElementById("")
returns a JS object that represents the elementdocument.getElementsByClassName()
and document.getElementsByTagName()
both return an HTMLCollection, which is like an array, of the elementstextContent
(best for text), .innerHTML
, or .innerText
to access and set valuesdocument.querySelector("div#my-id > p")
- returns the first object that is a child p of a div with id #my-iddocument.querySelectorAll()
- returns a NodeList of objects that match the CSS query. Can conver to array with Array.from(myNodeList);
document.body.style.textAlign = "center"
- the style property is an object with CSS styles. Note text-align is changed to textAlign. (also, this is an easy way to get the body)
window.getComputedStyle(myElement)
to get a CSSStyleDeclaration that you can call .color, etc ondocument.querySelector("#header").className += " new-class"
- add a class to an element, but removal is difficultdocument.querySelector("#header").classList.remove("my-class")
- use add()
, remove()
, toggle
document.createElement("li")
myList.append(newLi)
- append() and prepend() adds the parameter element into the original, either at top or bottom
appendChild()
is similar, but more strict.append()
, you can use append("some string")
into a parent to look like <div>Appending Text</div>
. Not accepted with appendChild()
append()
does not have a return value, but appendChild()
returns the appended Node objectparent.append(child, childTwo)
for multiple children, but appendChild()
only allows a single childdocument.body.innerHTML += "<p>hi</p>"
to append. This doesn't create objects, just takes in a string. Generally okay for simple text where you don't need control over the objectunwantedElement.remove()
or parentElement.removeChild(unwantedChild)
myElement.addEventListener("event", function);
myElement.onclick = () => {...}
because it allows multiple events, but onclick is quick and easy.Promises
An object that may produce a single value some time in the future for if the value is not known when the promise is created.
A promise can only be in one of 3 states, and once it reaches a resolved state, it cannot be changed: pending, fulfilled, and rejected.
The promise constructor takes in a function with two function parameters, resolve(), and reject(). When it reaches either state, the message will be stored in the variable.
Every promise object has a .then()
method that takes in 2 optional callback functions for the success and failure cases of the promise. Because .then()
returns a new promise object, it is possible to chain promises. This allows us to mimic synchronous code with asynchronous functions.
Promises are built on top of callbacks to write sequential asynchronous code with error catching.
They're used for network requests such as fetching data from an API or in other asynchronous functions.
^ To catch errors that may even occur during the .then()
, you can pass only the success parameter in .then()
, then chain on a .catch()
for the error
To create a timeout promise that will invoke if the other(s) are taking too long, use Promise.race()
:
^ This also uses IIFE (Immediately-Invoked Function Expression), which is an anonymous function that immediately invokes because of the ()
.
Use Promise.all()
to run Promises synchronously, to return an array of their responses after they are all done
Advanced ES6+
const myFunc = food => `I want to eat ${food}`;
returns the string. lots of shorthand can be used, like no () and no {}. Can set a default value for parameter(s) in case one was not passed in by setting (param = "defaultValue") => ...
get
binds an object property to a function that will be called when that property is looked upstatic
function can't be called on an class instance, but on the class itself as a utility (Animal.whatIs()
)const arr = ["a", "b"];
const arr2 = [...arr, 1, 2];
console.log(arr2); // ["a", "b", 1, 2]
const arr = ["a", "b", "c"];
const [first, ...theRest] = arr;
console.log(theRest); // ["b", "c"]
function myFunc(...args) {
//args = ["a", "b", "c"]
}
myFunc("a", "b", "c");
var
sucks because it uses variable hoisting. When js sees a var, it immediately declares it in global scope, even if its initalized value can only be accessed inside somethingexport const data = [1,2,3];
(in example.js)import { data } from './example.js';
(in main.js)
.then()
method to chained asynchronously
response
is a js Response object, which you can call methods .text()
, .json()
, .blob()
, etc. to get the data in the format you want. These methods return Promises containing the data, so you need to chain another .then()
:async
function converts the return to a Promise object.await
in an async
function. Await can be put in front of any async promise-based function to pause your code on that line until the promise fulfills, then return the resulting value.then()
chainsasync
function returns a Promise, so to access a return from an async function, use:
ayncFunc().then(result => console.log(result));
try/catch
block, or do the following:
Response.ok
- boolean of whether the response was successfulResponse.status
- status code of the response (200 for success). Alternatively, Response.statusText
will return "OK" for 200.`${fname} ${lname} has ${num1 + num2} cats.`
... using ${} to access variables, easier to manipulate strings. Can also type multi-line strings insideconst {name, address: {city}} = person;
is the same as const name = person.name;
and const city = person.address.city;
const [fName,, lName] = ['Lily', 'n/a', 'Peng'];
function address(city, state) {
console.log({city, state});
}
address('NYC', 'NY');
{city: NYC, state: NY}
Closure
Closed Over Variable Environment (COVE)
Creating persistent memory (variables/data) from an outer function accessible to an inner, generated function. Every function created receives data from the memory space where the function definition lives (normally global).
Memoization
A technique of storing the results of function calls and returning the cached result when it receives the same input again. Helps to optimize performance by not calling expensive functions more than once.
Built upon the concepts of closure and higher-order functions (returning functions from functions).
Event Delegation
Add event listeners to parent instead of child elements. Uses less memory (don't need one for every child) and don't need to unbind and rebind for different children.
To avoid event bubbling (events playing from bottom element to top), use: event.stopPropogation();
JS Modules
Sectioning your code into self-contained parts that are not dependent on each other, so you can make changes without disrupting everything else. Allows you to not worry as much about sharing global variable names.
Types of For Loops
for: i
= index, arr[i]
= item
for in: i
= index, arr[i]
= item
array.test
iterated with 'for in' will print that value in the array)forEach: v
= item, (optional) i
= index
this
(function context). By default, the 'forEach' this
will always be the global object (window)for of: v
= item, use Array.entries()
to access indexes
Declare vs. Initialize vs. Instantiate
Declare - var a;
Initialize - var a = 10;
Instantiate - MyObj x = new MyObj();
//create a new instance of a class
Regular Expressions (RegEx)
/ab*c/
means 'a' with zero or more 'b's and one 'c'/a\*/
/\d{4}/
means a digit, 4 times. Digit is same as: /[0-9]/
/^[a-zA-Z]+$/
matches any English character(s). ^ means beginning, + means 1 or more times, $ means end. So it won't match if the characters are in the middle of the string, only if the string only contains these characters.()
means a capture group.regex.test(str)
- return true/false if regex in strstr.search(regex)
- return index of first regex occurence in strstr.match(regex)
- return an array with value of first match and the capture group(s) (if any) it matchedg
(global flag) was used at the end of the regex, it will return all matches and none of the capturing groupsregex.exec(str)
Sample Challenges
arrayReplace(array, elemToReplace, substitutionElem)
- write 1 line of code to solve: e.g. [1,2,1] elemToReplace 1 & substitutionElem 3 = [3,2,3]
return array.map(e => e === elemToReplace ? substitutionElem : e);
caseInsensitivePalindrome(str)
: 1 solution using array/string functions, and 1 solution using smallest big-O
factorial(num)
:
duplicate([1,2,3]);
// [1,2,3,1,2,3]
.concat()
FizzBuzz
(print numbers, but multiples of 3 are "Fizz" and multiples of 5 are "Buzz")pangram(str)
// pangram is a string that contains every letter of the alphabet at least once
add(2)(3)
, which gives sum of both numbers. Functions are first-class objects, meaning they are treated like any other variable. So calling add(2)
returns a function that takes in a parameter (3)
and that one returns the result.
Map()
2021 Lily Peng