These are the starter files and solutions to the Beginner JavaScript course
- Adding
asyncto ascripttag will tell it to load asynchronously - Adding
deferto ascripttag will tell it to wait until everything else is loaded first
typeofto get type- Plus sign will concatenate strings so be careful
Math.helper methods are useful.round,floor,randomandceilare most commonly used- The Modulo
%will give you the remainder of one number divided by another - Don't store money in dollars and cents, just use cents and round it
- Integers are whole numbers and floats have decimal points
undefinedis when you try to access a variable that has been created but not set to any valuenullis when a variable has a value explicitly set to nothing
- Almost always use triple equals
- Triple equals checks for the value and type of the things being compared
- Double equals only checks the value of the things being compared
navigator.vibratecan vibrate phonesscrollTocan scroll to a section of a page
console.countwill count how many times a function has run
- Closure is accessing parent level scope from a child scope even after the parent function is dead
- You have to return the child function in order to access the parent functions variables
- Navigator gives you information about the device
- Window gives you information about the browser
- Document is everything from the opening HTML tag to the closing one
- Use
document.querySelectoranddocument.querySelectorAll
- Use
console.diron an element to get the available methods and properties - Use
.textContentto get an element's text content - Use
.insertAdjacentTextto add text to an element
- JavaScript has ClassList methods,
.add,.remove,.toggle,.contains
- Attributes refer to the additional info on an element
- Some are just getters like
.naturalWidth
window.addEventListener("load", function() {
console.log(element.naturalWidth);
});
// OR
element.addEventListener("load", function() {
console.log(element.naturalWidth);
});- Use
data-for custom attributes - To get data on an object, use
.dataset
- Use
document.bodyto append to the body of the page - Use
.insertAdjacentElementto add element next to another - Also,
.cloneNode()is good for cloning elements
- We can create elements using
document.createRange().createContextualFragment(markup)and filling it in with text that will be converted to HTML that can be read by the browser
.childrenare only elements while.childNodesare elements and text- The method you want to use is going to depend on whether you're starting with an element or a node and whether you're trying to interact with an element or a node
- use
{once: true}on event listeners to call it and remove it in one shot
event.currentTargetis the thing that fired the event listener, so if you have a button with a nested element, thecurrentTargetwill reference the button and not anything inside itevent.stopPropagationwill stop your event from bubbling up- You can set events to listen at the capture or bubbling phase using the
{ capture: boolean }option
- Use Preserve log to preserve things that happen in the console!!!
- Buttons and links should not be mixed up
- Use
role="button"andtabindex="0"to ensure things are focusable keycode.infois the best website
- Use
.closestto find the thing you want the user to click
- Here we use the Intersection Observer, which consists of instantiating the observer with a callback function and some options, telling it to observe something and then doing things with that action
- This was done in a JS File in the repo
- BEDMAS = Brackets, exponents, division, mulitiplication, addition, subtraction is the order of operations in JavaScript
- Once an
ifstatement finds a true condition, it stops - Try to keep logic out of if statements
- Truthy values are things like empty or fill in strings
- Coercision is forcing a non-boolean into a real boolean
- Double bang will convert a value into it's boolean value
- Don't forget the
&&trick
Blockless If Statement
if (thing) runFunction();- Built a turtle!
- When you use a timeout, javascript will keep going and come back to the timeout later
- Always use trailing commas
- Use
Object.freeze(object)to create an immutable object that locks down an object's properties - You can use
deleteto remove a property on an object
- When you compare two objects, they usually will not be that same unless they are the exact same object
- When you create a variable that references an object (
object2 = object1), upating the reference (object2) will update the original object (object1) - If you pass an external object into a function, you can modify data that lives in that external object
How to properly copy and object
// Shallow Copy
const objectCopy = { ...objectToCopy };
// Deep Copy -- requires Lodash
const deepObjectCopy = _.cloneDeep(objectToCopy);- Maps are similar to objects
- A Map's order is set in stone
- A Map's key can be set to anything as well as the value
- Use a map if you need to maintain the order of the items
- Maps are for storing data
- Maps can't have methods
- If you need to send data, you have to put it in an object
const map = new Map();How to properly add to an array
const updatedArray = [...array, newValue];
// OR
const updatedArray = [newValue, ...array];.slicereturns a portion of an array and is immutable.splicetakes an item out of an array
- When you store an array with
.pushas a variable, it will return you the new length of the array for some reason
.sortturns items into strings and then sorts them, to sort numbers you need to create a callback function
- Using
.forEachyou can get the item, index, and array as well as thethis - Doesn't return anything
.mapis for performing an action on data and returning it
- Skipped
- The second argument in
.reducetells it where to start
- This is useful for looping through an array. Although
.forEach, .map and .reduce has replaced ithas pretty much replaced it. - The only real use for it is when you have to increment by a specific number at a time
for(let i = 0; i <= 10;i++>) {
console.log(i);
}- Used for looping over iterables
- Useful for emojis, sequencing data
- Mostly useful for sequencing promises
for (const letter of name) {
console.log(letter);
}- Returns the keys of an object
- This does look into the prototype of an object
for (const letter in name) {
console.log(letter);
}- Not super useful
let cool = true;
let i = 0;
while(cool === true) {
console.log('You are cool);
i++;
if ( > 100) {
cool = false;
}
}
// Do While
do {
} while() {
}- Finished!
- Code in
exercises/56 - Sarcastic Text/text.js
- Code in
exercises/57 - Shopping List/shopping.js
- Code in
exercises/58 - Gallery/gallery-V1.js
- Code in
exercises/59 - Slider/src/slider-v1.js
- The
newkeyword creates a new instance of an object
- Remember that arrow functions bind
thisto the parent object
- Code in
exercises/58 - Gallery/gallery-v2-prototype.js
- Add functions to the prototype so they can be shared by all instances of a Prototype
- Code in
exercises/59 - Slider/src/gallery-v2-prototype.js
.bindWill manually bind a function call to a particular thing you select- First thing passed to bind will be
thisand everything else will be the regular arguments
.callwill do the same things as bind but then also call the function
- The only difference between
.calland.applyis that apply requires an array of arguments
- JavaScript is single threaded, so only one thing can run at a time
- Code in
playground/promises.html
- If you have a chain of promises, they will stop executing if there is an error
- Asynchronous functions return a promise
- Code in
exercises/72 - Async Prompts/scripts.js
- Code in
exercises/73 - Async Typer/scripts.js
- Code in
playground/apis
- Code in
exercises/75 - CORS and Recipes/scripts-fl.js
- Code in
exercises/76 - Dad Jokes/jokes.js
- Code in
exercises/77 - Currency Converter/money.js
- The VSCode Extension
Live Serverby Ritwick Dey will create a super simple Server for your project - You can also globally install
browsersyncand then use thebrowsersynccommand from the directory you're working in
- Code in
exercises/77 - Currency Converter - Modules
- Code in
exercises/76 - Dad Jokes - Modules
Dealing with regeneratorRuntime issues:
"browserslist": [
"last 1 chrome versions"
]- Delete the
type="module"from your script tag when using Parcel
- Use
Fakerto generate fake data for projects!
import { name } from 'faker';
console.log(`Hello, ${name.firstName()}`);- Don't store price or API keys on the client without validating on the server
- Use a sanitizer like
dompurifyto keep HTML sane - Always send data to HTTPS
- Code in
exercises/84 - Web Speech Colour Game/speech.js
