Vanilla Javascript Cheatsheet
Variable Declaration and Assignment
var- Declares a variable scoped to the current functionconst- Declares a variable that can never change and is scoped to the nearest block (if,for,else) or functionlet- Declares a variable that can be change and is scoped to the nearest block (if,for,else) or functionleft = right- Fully evaluates the value of the right side THEN assigns that value into the left variable
Logic Operators
==- Compares left and right value (but not type) returns true if they are the same!=- Compares left and right value (but not type) returns true if they are not the same===- Compares left and right value (including type) returns true if they are the same!==- Compares left and right value (including type) returns true if they are not the same<- Returns true if the left value is less than the right value (tries to make things the same type)<=- Returns true if the left value is less than or equal to the right value (tries to make things the same type)>- Returns true if the left value is greater than the right value (tries to make things the same type)>=- Returns true if the left value is greater than or equal to the right value (tries to make things the same type)
Math
left + right- Returns the sum of both sides (does not change the value ofleftorright)left - right- Returns the result of subtracting the right side from the left (does not change the value ofleftorright)left * right- Returns the product of two sides (does not change the value ofleftorright)left / right- Returns the result of dividing the right side from the left (does not change the value ofleftorright)left % right- Returns the remainder after dividing the right side from the left (does not change the value ofleftorright)left += right- Returns the sum of both sides then sets the left side to the resultleft -= right- Returns the result of subtracting the right side from the left then sets the left side to the resultleft ++- Returns the sum of left add1then sets the left side to the result (same asleft += 1)left --- Returns the result of left subtract1then sets the left side to the result (same asleft -= 1)
Blocks
if (statement) { }- Checks if the statement in parenthesis is "truthy", if so run the code in the block, otherwise skip the block entirelyif (statement) { /* ifStuff */ } else { /* elseStuff */ }- Checks if the statement in parenthesis is "truthy", if so only run the code in theifStuffblock, otherwise only run the code in theelseStuffblockwhile (statement) { /* ifStuff */ }- Checks if the statement in parenthesis is "truthy", if so run the code in the block, when the block is complete make check again and repeat until statement is "falsy" (could be endless...)for (/* initialize */; /* statement */; /* change */) { }- Similar to awhileblock, but has an initialize step that only occurs once, and after the loop run thechangestatement before running checks
Strings
`${javascriptInHere}`- Inside of`s, when you encounter a${}evaluate the stuff in the curly braces as Javascript and put it right there in a string:const x = `Hello`; const y = `${x} World`;The variableywould be"Hello World".length- The number of all characters in a string.split(separator)- Return an array of strings splitting on the passed in separator and removes all separators:const x = `Hello`; const y = x.split(`e`);The variableywould be["H", "llo"]
Arrays
[]- Creates a new empty array (values can be put inside separated by commas).length- The number of entries in the array.push(a)- Modifies the existing array and adds passed in value to the end of the array.forEach(cb)-.map(cb)-.reduce(cb)-Accessing Items
const x = [`1`, `2`, `3`];
/**
* Remember array positions start at 0
* and goes to (.length - 1)
*/
const y = x[1];
console.log(y); // "2"
"Array Like" Objects
Array.from(arrayLike)-
DOM - Document Object Model (What the user sees and interacts with)
document- The loaded page in the browser as an Objectdocument.querySelector(selector)- Returns the FIRST element matching the selector ANYWHERE on the page. If none is found, returnnulldocument.querySelectorAll(selector)- Returns a list elements matching the selector ANYWHERE on the page. If none are found, return an Empty Element Listdocument.createElement(tagName)- Returns a newly created element in memory (not shown to the user yet) with a giventagName
Elements
.querySelector(selector)- Returns the FIRST element matching the selector within the element. If none are found, returnnull.querySelectorAll(selector)- Returns a list elements matching the selector within the element. If none are found, return an Empty Element List.classList- An "array-like" list of all the classes for an element.classList.add(name)- Adds a class to the element if it doesn't already have the class.classList.remove()- Removes a class to the element if it's there, if not do nothing.classList.toggle()- Adds a class to the element if it doesn't already have the class, removes the class if it already exists in theclassList. Returnsfalseif class is removed, returnstrueif class is added
.innerText- Reads the text content within an element.innerText = something- Sets the text content of an element (escapes special characters or HTML).innerHTML- Reads the HTML string content of an element.innerHTML = something- Sets the HTML content of an element AND parses all content as HTML - Example.textContent- READ ONLY: Escaped version ofinnerText.style- Object containing the inline style properties for an element.addEventListener(eventName, callback)- Registers a callback function to be run when the event named byeventNameis fired
Timing Things
window.setTimeout(cb, t)- Runs callback function oncecbafter AT LEASTtmillisecondswindow.setInterval(cb, t)- Runs callback functioncbafter AT LEASTtmilliseconds and then continues running AT LEAST everytmilliseconds after the last run
Promises
Promises give structure around waiting for asynchronous tasks or events.
new Promise(cb)- Creates a new promise object and runs the callbackcbimmediately- Promise Callback Format
- Receives two arguments
- Resolve - A function to run when finished successfully with asynchronous tasks and can accept data
- Reject - A function to run when finished failing with asynchronous tasks and can accept data
- Receives two arguments
- Using Promise Objects (Assume
pis a instance of a Promise)p.then(cb, cb2)- Runs the callbackcbonce the callback has resolved successfully, orcb2if the promise is rejectedp.catch(f)- Runs the callbackfwhen ANY promise has failed
Promise Example:
function askForUserInput(resolve, reject) {
if (window.confirm(`Should this resolve`)) {
resolve(`HEY`);
} else {
reject();
}
console.log(`This is in the promise`);
}
var p = new Promise(askForUserInput);
function onSuccess(message) {
console.log(`YAY`, message);
}
function onFailure() {
window.alert(`BOOO`);
}
function catchAll() {
window.alert(`CATCH`);
}
p.then(onSuccess, onFailure).catch(catchAll);