is learning Javascript hard? Free Tools Is learning JavaScript Hard? This is a question I will soon find out the answer to. I have NO coding experience. Zero! Born in a generation before coding was part of the school curriculum and so I had no exposure as a child and my undergraduate degree was life science – so I avoided over-loading my schedule with “hard” computer science courses (big regret). However, I believe with that past it makes me the perfect guinea pig for this experiment and I’ll document this journey in this single post with daily progress. By the end hopefully together we’ll have an understanding of how far we can expect to get in a specific time frame and see what kinds of things we’ll be able to build by the end. Background about me and current headspace: I am currently 25 and decided I want to learn how to code. It’s something I’ve known I’ve wanted to do but didn’t know where to start. Whenever I googled what language should a beginner first learn the answer I got was, “well it depends on what you want to create” ?‍♂️. I guess they’re not wrong, but c’mon… just tell me exactly what to do. Learn X and then you’ll be able to create the next big social network! But if I am being honest I think what I was hoping to find was a blueprint, a prescription of some sort. No such thing exists. It was a mental trap and I never got anywhere, I procrastinated, I put off the learning and was too afraid to begin doing the work because I lacked clarity. Well…not anymore! Where I hope to be at the end of this: If there was no destination I don’t think I’d ever start the journey to learn JavaScript. There is a personal goal and for each person, it’s probably different. I’ll explain why I decided to learn JavaScript first. For the past 2-3ish years, I’ve been building a portfolio of WordPress websites using a website builder, this required minimal to zero coding knowledge. And as much as web-developers like to shit on builders, it’s been great for me. These projects have made me realize the role that content plays in our lives and business, I learned how to do SEO, marketing, and dabbled in basic graphic design in Adobe CS6, Illustrator, and After-Effects. These separate but complementary skills helped me get some of my sites ranking well in Google bringing in free organic traffic to my sites every month (pretty cool). Now that I have more and more people looking at something I created online I found myself getting frustrated and limited by what the website-builder could do, not necessarily what I wanted to make. I want to be able to create dynamic and awesome looking content, tools, unique applications. This would help the SEO by attracting links from other sites and further help me outrank my competitors and get more eyeballs. I rationalized that if I am intend to spend the next 5-10 years creating stuff online, I should learn the language of the web which is HTML, CSS, JavaScript (that or I outsource it but since I can’t afford to hire, looks like I am going to wear that hat.) In short, I just want to try and build cool web applications people like and use and maybe I can get paid in the process. The worst-case scenario I foresee happening is I learn to code and with that specific knowledge, I may be able to get freelance gigs and help clients with their websites (a pretty good bad case scenario). I see many posts about coding boot camps and whether academies will help them land a job as a junior developer job. This is not the route I am looking to take, I want to keep my learning expense for coding to a minimum and don’t really care to be accredited. I’d personally go the freelance, content creator route, maybe even into web hosting reseller where I would host, build, and consult SEO. Day #1 – Self Taught JavaScript Programmer Bought a beginner JS courses for $39.00 total from Udemy. I know there are many free reputable courses on YouTube you can follow along with as well. The thought is to find someone that’s trustworthy to teach you modern best practices and teaching style is fun, and engaging. Going to go through one course fully before jumping around. The course is ~40 hours of JS. I am also going to try and study full-time unless other commitments pop up. I mentally prep myself by just accepting this month is going to be a grind. Embrace the suck and try not to get discourage. Hopefully, by somewhat journaling and writing notes here I’ll be forced to recall and engage with the material to help further commit things to memory and true understanding. 4 hours spent Topics covered: What exactly is JavaScript and what is a programming language. Linking a JS file at the end of the </body> tag in your HTML file Introduction to Chrome developer console + console.log( ) Creating variable and values (camelCasing naming convention) 7 Primitive data types (number, strings, boolean being the main three, null, undefined, BigInt and symbols.) Commenting in JS (// comment – in visual code studio the short-key is Ctrl + /) Variables, constants, and var (variables are mutable, constants are not) Basic operators like +, -, /, ** (exponent), and % (% is called mod – tells you the remainder 3 % 2 would be remainder 1) and order precedence Strings and Template literals (template literals make writing easier denoted with backticks “ and allows you to write JS expressions inline using ${ } ). Decisions making in JS – If, else if, and else. Conversion (strings to number or numbers to strings using function Number() and function String()) Type Coercion (the use of + automatically concatenates instead of adding. Other operators like – * / behave normally. If the string is a number using – * / will convert it to a number. Not knowing these rules can cause bugs in your code. Having bugs in your code just means errors or unexpected results.) Truthy and falsy numbers (falsy values are: 0, ‘ ‘, undefined, NaN, Null – again not knowing how these rules work can cause bugs in your code.) Equality operators (=== strict operator, only will work when the values are the same type. The == does type coercion meaning it will convert the string ’18’ == to number 18 and that would be true.) Boolean logic (&& means A and B, and || means or, ! is NOT meaning it inverts or reverses, so these are equivalent !true === false) Switch cases (remember to use break; after the case otherwise it will execture the rest of the JS code). Ternary operation – allows you to write condensed if/elseif statements into one line using ? separating options with a colon. E.g. console.log(`able to drive ${age >= 16 ? “yes” : “no”}`) The ternary operator should be used for a quick decision. If else is better for bigger decisions) End of day: A lot of technical jargon, looking back at the notes seems daunting but if you follow along with a course it doesn’t seem all that bad. With HTML and CSS you can build a site within the first few lessons and begin tinkering which is encouraging feedback. After day #1 with JavaScript, I can write code that’s being executed in the console of chrome to solve basic math problems. The exercises seem to be geared towards familiarizing us with writing and understanding JavaScript. There seems to be a lot we’ve got to learn before we can make anything meaningful which can be discouraging. But then I remember this quote by Jim Rohn that says, “If the promise of the future is clear, the price to pay is easy”. Googling applications made with Javascript helps find the promise. Day #2 – Arrays and Objects 3 hours spent Topics Covered: Arrays (use square brackets [], arrays can hold a collection of data in an ordered list, they don’t have to be of the same type. E.g. songs in a playlist) Each string is indexed meaning each character has a position and can be called upon. The first character starts at zero, so people[0] = ‘p’. Similarly, an array has positions, and you can ask to deliver whatever is being held in that slot. The data or element contained in an array can be changed and rearranged (e.g. colors[0] = “green” will update whatever is the first position to green. You can even change the type of data). There are many array methods, you can find them all at MDN and don’t need to memorize. Just remember all array methods require parenthesis. The main one, Push – pushes data to the end of an array. Pop – pops out the last element from the array. Shift – removes from the start (think ctrl, alt shift, delete). Unshift – adds to starts. The syntax for arrays methods, you write the array name, movieLine.push(‘new entry’) Then you also have concat, includes, indexOf, join, reverse, slice, splice, and sort. Concat (adds two arrays together) Includes (tells us if something is stored) indexOf (tells us if something is in the array but also tells the position, but will only tell us the first use. Not repeated if there’s multiple.) Reverse (destructive – changes the original and reverses) slice (0,3 will output whatever starts at zero (including) and stop at 3rd position (exclude)) Splice – Cuts / Replaces (or you can add) – lineUp.splice(_,_,_) (where the first position you want to add or remove, 0 to not delete the next terms or 3 to delete next 3 terms, what you want to add) An array doesn’t have any value, but rather is like an address or reference of where that container exists in Javascript memory. Even though the contents may be the same [1,2,3] === [1,2,3] will return false. To make this true, a = [1,2,3] and let b = a. B is now referencing the same location in memory, testing now, a === b will be true. Good practice to make an array a constant, the address won’t change but the contents inside are flexible to change. Within arrays you can store arrays, you can index different levels, gameBoard[1][1] reads 2nd listed array, 2nd position. The problem with arrays, is they are just a list, introducing objects. These are collections of properties that have a key and then a value. If you know the key, you can get the value. (They exist in pairs, use curly braces, const person = {Age: 20, Country: ‘Canada’}) With object literals, you can nest Arrays within them using square brackets. Access info out of object the syntax is weird, use person[“age”], square brackets + quotations and then the key, you could also do person.age. The reason why you need quotations is that inside the bracket it will execute the code, if you just enter person[age] it will look to evaluate the variable age but it was never assigned. And inside your {object} it won’t assign the key as a variable. Age is simply converted or treated as a string. So using square brackets good for when you want something dynamic, otherwise, dot notation is easier to type and use. You can also make a new entry to an object by just writing people.new-entry. After creating the entry you can assign the value, people.new-entry = “3”. Let’s say you have an array titled game, and within that, an object nested. You could pull data from the object, array[1].lives. This will go to the 2nd positioned array and find the key under “lives” and output the value. End of day: Working with arrays and objects is more engaging. With 6 hours of JS under my belt can’t really say I can use any of it in a meaningful way. If I learn regular expressions can write a script to modify or replace all keywords in a given piece of text which is kinda cool. But really could’ve just gone to Word document to do that. But knowing I don’t have to rely on Microsoft word documents to do that is a small win and I’ll take it. Day #3 – All about loops (for loops, nested loops, for…of) 6 hours spent Topics covered: Spent 3 hours reviewing the past lessons and writing code, did some practice exercise found on Google for basic problem sets using if, else, and loops. For loops, format (let i = 0; i <= 10; i++) { console.log(i); } this will run a loop until the condition less than or equal to 10 is no longer true. So we start at i=zero and will increment by i++ (which is one) all the way up to 10, it will go to 11 but the condition is no longer true and stop looping. The console.log(i) will print this in developer tools 0 to 10. Be careful with loops, understand when the loop will end because an infinite loop can cause problems. You can also loop over arrays, making conditional statement something like i < array.length; or i<= array.length -1; Just remember when your printing something in the console.log, it’s an array, console.log (array[i]) following the array syntax where i is the iterating loop you defined in the for loop part of the code. You can nest loops. The outer loop will run once, the inner loop will be executed all the way through for each step of the outer loop. In this case you have a nested Array, seatingChart[0] just gives you the first array. But using nested loop with variable row allows us to list the items within that first array. And so the loops continue doing this for every array. Example: const seatingChart = [ [‘Kristen’, ‘Erik’, ‘Namita’], [‘Geoffrey’, ‘Juanita’, ‘Antonio’, ‘Kevin’], [‘Yuma’, ‘Sakura’, ‘Jack’, ‘Erika’] ] for (let i = 0; i < seatingChart.length; i++) { const row = seatingChart[i]; console.log(`ROW #${i + 1}`) for (let j = 0; j < row.length; j++) { console.log(row[j]) } } While loops, will keep running while some condition is true. It’s easier when writing while loops to get caught in infinite loops, be careful and think about how it will end. It’s more useful if you don’t know how many times to iterate, like typing a secret password, want to allow keep guessing until it’s right. Or in a game of chess, keep looping until the game is over, however many turns it takes. Here’s basic example of writing a while loop but useless case.let num = 0; while (num <10) {console.log(num); num++;}You can also add break; to a while loop (or even for loop). So if some condition is met, (e.g. guess num === target num) you can break out of the loop and run JS code outside the loop. For…of is an easier way to write, read, and iterate over arrays. As in the example of seating chart example. General format (your_variable + of + some iterable thing) followed by statement using that variable.for (let row of seatingChart) { (for students of row) {console.log(students) }} For…in is used when iterating over objects (not very common). If you don’t want to work with objects you can convert object under new variable as an Array using, Object.keys(objectVariableName) or Object.values(ObjectName) or to create an nested array with both key,value for each entry, Object.entries.End of day: Was able to follow along and understand how to code a to-do checklist where a user could input new entries into a list and delete any item from a list. Wasn’t able to code myself independently but ability to understand someone else’s code and logic applied. Still not able to create something of value for a specific end user – just for myself use prompt function and the console. Day #4 – Functions: 5 hours spent Topics Covered: What are functions (syntax: function functionName ()), multiple arguments, the return key. 3 hour practice of writing basic functions exercise. Visibility of variable or scope in JavaScript (any variable defined in a function can’t be called outside of the scope of that function). Block scope, using let inside a function or a loop (basically anything within curly braces is considered a block) then that variable is confined to that block. It can not be called upon outside that function. Whereas if you use var for your variable it can exist outside the block and be called upon. Lexical scoping – an inner function nested inside of a parent function has access to the scope or the variables defined in the scope of the outer function. It doesn’t work the other way though, a variable created in an inner function using let cannot be called upon in the most outer function. function expression, there’s no function name required as you’re storing the function in the variable, just like you would an array. Const area = function (l,w) { return l*y; } Higher order function, the ability to pass around a function as the argument in another function. You can also return a function as a value from within a function. Creating factory functions or a returning function. It’s pattern you may see for coming up with a new function based on meeting a specific condition. For example: . function makeBetweenfunc (min,max) { return function (num){ return num >= min && num <= max; } }Explained: you can set makebetweenfunc with a range, for example is child 0,18. You can store that as a new variable (let isChild = makebetweenfunc(0,18) and in doing so you’ve created new function since it’s return would be isChild(3) which will execute the condition and be true). What are methods? Every method is a function, but not every function is a method. A method is function which is a property of an object, it tells you about the object and you can change the value of one or more objects. So, we have objects (example: hotel, properties: rooms, methods: make a booking). Know that you can store a method as a property on some object. This happens very often, there is a shorthand way for adding methods. Pay attention to the commas after the function to separate each entry. LONG WAY: const math = {irrelevant: ‘mike’, add: function(x,y) {return x+y;}, third: ‘3rd’, }SHORTHAND: const math = {irrelevant: ‘mike’, add(x,y) {return x+y;}, third: ‘3rd’, } This keyword, This references an object that’s executing the current function. Most commonly used inside of a method within an object. Trying to call another property within an object can be useful but can’t be done because it’s not a variable, but with ‘this’ you can refer to other properties within the object. However, it’s more complicated, depending on the invocation context of the function ‘this’ is used in will change the value. When it’s not within the object it become part of the global property of the window object (the highest level object in every browser). End of day: There’s a lot of syntax and understanding of rules, it can seem like a lot. Need a lot of practice writing to catch places where I am forgetting a colon or a comma… necessary growing pains. Still limited to just using the console, will keep pushing through but so badly want to be able to begin working JavaScript with HTML and CSS in a doc. Day #5 – Try/Catch + Callbacks and Arrays 4 hours spent Syntax for try/catch, try { [your JS code] catch { log.console(After!) } } It will tell you whether or not there’s an error in the code. It will catch it. The rest of the code will still execute. This is also really important when working with APIs, if they are not reachable for whatever reason baking in the try and catch can prevent the whole app from crashing. Arrays and callbacks, foreach, map, filter, reduce, and arrow functions. foreach, will run each entry in an array through a function. For example, numbers.foreach(function (el){console.log(el} In the past this was the number one method, but now you can also use ‘for of’. Map is like for each where it callbacks each element in an array through a function you define, but the difference is it returns or maps it out in a new array. This offers us the ability to change every element in an array. For example, you can all caps characters, capitalize the first letter in an array, double every value. Arrow functions are a new syntax that shortens and makes writing expressions a lot easier. Like function expressions they can’t exist in the wild, they need to defined with a variable name. So, const add = function(x+y) {return x+y;} can be summarized to const add = (x,y) => {return x+y;} For single parameter const add = x => {return x+y;} (can ignore parenthesis, for empty or double parameters you need parenthesis). You want to shrink the arrow function even more? Well you can with implicit arrow function which is only for arrow functions which only return one thing. So we go from const add = x => {return x+y;} to const add = x => x+y. It’s single line of code, understands you want to return x+y. Only works if there’s one statement or only one thing to evaluate. If there something that needs to be evaluated like math.random() instead of using curly brace + return you can replace all that with just putting the math.random() in parenthesis. setTimeout just adds pause or delay between code, setTimeout(function(), 3000); setInterval follows same syntax but adds an interval of how often it should be repeated. You can stop this from running by defining a variable const id, and then clearing it by clearInterval(id) Filter, creates a new array with all the elements that pass through the test implemented by the provided function. The conditional function has to return either true or false (boolean value) if it’s true that element is added to the new array, otherwise it’s ignored. You can chain the functions together, the filter immediately followed by map to get, movie.filter(m => m.score>80).map(m => m.title); Some and Every are boolean callbacks that test each element in an array. Every will check each element and if they pasts the function you define, it will say true. Some will test whether any element passes the criteria, if it does it will return true. reduce (did not really understand…review in detail – moved on) The keyword this behaves differently in an arrow function versus regular function. Default Params – when no input is inputted to your function you want to default it to a value. For example, rollDie(numSides = 6). End of day: Can write basic functions to solve a problem like sorting through a database of thousands of moving and finding the highest rated one. Can filter through and find most recent releases by rating. But the problem with this is the database would have to be provided so not sure how practical that is. Still all code exists within the console for personal use, not for an end user. Day #6 – Newer JS features + DOMS Hours spent 5 hours: Spread expands arrays, object, object literals, and even strings into a list of arguments. This way you can pass through an iterable into a function call. Syntax Math.min(…Arr). You can create a brand new array using two old arrays adding your own new element as well […old, …old2, newElement] The same can be done with objects but syntax is with curly braces. Just note if they have the same key with different value, the value that wins will be the one that’s last. The rest param, collects all argumenets and puts it into an actual array. It looks like spread but it’s not, spread will take an array and spread each entry into an individual argument. E.g.: function(…nums){ return.nums.reduce(total, el)=> total + el) } if you had tried this without the… it will only accept a single parameter. Arguments also don’t work inside arrow functions which is another reason to use the rest parameter. Destructuring Arrays, const [gold, silver, bronze, …everyoneElse] = Scores. Here Gold is a new variable created which will take on the first position of the array scores. Destructuring Objects, {email, name, lastName, born: birthYear = ‘N/a’ } = object. Here we created a new variable for each email, name, lastname all in one line. We also changed the name, we call upon the key value born changed it to birthYear. If it is undefined (as the entry does not exist) the default parameter will be N/a because = ‘N/a’ we specified. Destructure parameters when passed in a function: Instead of movie.map (movie => {return `${movie.title} (${movie.year}) is rated ${movie.score}` }) Shortened: movie.map(({title, year, score}) => {return `${title} (${year}) is rated ${score}` }) DOMS stands for document object model. Each element of a document is an object in JS. If you go to the console you can type document or type console.dir(document) which is a directory of everything JS recognizes on the page. Like with CSS you can select certain elements, like all links turn them blue. This is handled by the getElementId. When you call it, it must be a string. Note, when you call on an element by ID your not getting the HTML, you’re getting the DOM object. You can markup each thing you would like to call with a specific id tag you create, but that’s not the only way to select an object. Once you call upon the object version of that HTML element you can then begin to manipulate it using JS. You can assign it to a variable. const banner = getElementById(‘string’) – Get an element by the Id assigned to an element. getElementByTagName(‘img’) – get all images getElementByClassName(‘definedclass’) – all div class. The three above are a bit older ways, but now you can do it with query selector using CSS conventions. document.querySelector(‘h1’ or ‘#id’ or ‘.class’) you can also do document.querySelectorAll(‘p a’) Notice the p (space) a which is the descendent selector in CSS. All anchor tags in a paragraph. With DOM elements (append, innertext, innerHTML) you don’t need to commit these to memory. Just know they exist and where/how to use them. The vanilla JavaScript like for loops, let, iterating should be mastered and committed to memory the other stuff isn’t necessary. Using the DOM elements, document.querySelector(‘p’).innerText will pull whatever is in the paragraph tag for the first p. You can replace all links in a document. const allLinks = document.querySelectorAll(‘a’) for (let link of allLinks){ link.innerText= “I am a link” } innerText just changes the text. inner.HTML will allow you to change the innerHTML like adding an <em>. getAttribute(‘class’)(‘title’)(‘id’) to retrieve the attribute of something. You can use setAttribute to change it (‘href’, ‘https://google.com’). You pass in a second argument which is what you want to change it to. For example, changing alt and src of an image with ID of egg using JS. const toChicken = document.querySelector(‘#egg’) toChicken.src = “https://www.flaticon.com/svg/static/icons/svg/3523/3523063.svg” toChicken.alt = “chicken” You can find all the styling of a element by first selecting and saving the variable. And then coding h1.style. This is a massive object showing all styles of the h1 elements. Just note, the object key is all camelCased, so font-size would be fontSize. Also worth noting, this only shows inline styling, not styles from the stylesheet. You can change the styling within the DOM, h1.style.border = “2px solid red” This add in-line style changes, no really recommended but you can set CSS properties using JS. Setting attribute overrides all other CSS but sometimes you want to add multiple CSS classes, this is best done using the classList. So it would be h1.classList.add(‘square-images’). You can also remove classList.remove. There’s even an option to toggle which is useful in case of creating accordions. To add or remove elements on events you need to tell JS where to add or remove. After defining a variable, firstbold.parentElement to move up one element, you can also do firstbold.parentElement.parentElement to move up the hierarchy by two. You can also move down with .children. You can also move to adjacent with previousSibling and nextSibling but just note, it may pick up a node (kind of like whitespace after an element) it’s often better to just use nextElementSibling or previousElementSibling. End of day: With the end of the day, I can see practical applications of improving productivity. I can iterate over 100 or thousands of div elements and add a class list at scale by writing a for loop. This beats doing it manually – which believe it or not I have done in the past for thousands of div elements. But hey, you live and you learn. Day #7 – Events Hours spent 5 hours. You can create a new element with const newIMG = document.createElement(‘img’). This just creates a new img but you need to save it to a variable and then add a source and tell it where to go. You can then do newIMG.src=”enter_file_source.jpg”. Now you can appendChild, for example in this case at the end of the body, document.body.appendChild(newIMG) There is a new way just called append. You can do multiple nodes at once, or you can add string directly to the first paragraph. You can also do prepend which will add to front instead of the end. If you want to insert adjacent to an element, there is adjacentElement(‘afterend’ or ‘beforebegin’, element) or an easier method would be just h1.before(element) or h1.after(element). An example of writing 100 buttons and appending it to a div with id container.for (let i=0; i<100; i++){ const btn = document.createElement(“button”) btn.innerText = “cool” const where = document.querySelector(“#container”) where.appendChild(btn) } Just as you can add and create you can remove. You can select and save an element in a variable and then go, var.remove(), leaving () inside empty. Onclick element, you can write this inline but that’s not recommended. <h1 onclick=”console.log(‘see you soon boi’)” To write in JS file, first define and select then btn.onclick = function () {console.log(‘you clicked’) } There are many “on” properties, see MDN documentation for that. You can also define a function name and then call upon that function onclick. btn.onmouseenter = scream; which would call upon the scream function. Best option for working with events, targetElement.addEventListener(‘click’, () => {alert=’you clicked me!’}) The reason for doing this is you can’t have two callback options for one property like onclick. With addEventListener you can have as many callback options as you want. You can also add objects like only run once. We can put a parameter in our event object of our callback function to capture it. It’s an object that’s constructed for us that tell us information about the object. btn.addEventListener(‘click’, function (evt) {console.log(evt)}) This can be used with keyup or keydown, there is also key (which tell you the key pressed) and code is the location (e.g. ShiftLeft – left shift key on keyboard, and is not language specific) Forms – A form has action=”” which often redirects, if you remove this when the form is submitted it will refresh the page. We can stop that with JavaScript using form.addEventListener (“submit”, function(e) { e.prevent.default() } The prevent.default will stop it from moving to the next step. Now we can extract data by using the name field created on the form and saving the value placed by the user. This would look like, const usernameInput = tweetForm.elements.username; where tweetForm is a saved targeted element of the form created in the markup. (it’s recommended to define name of your form, otherwise you would need to queryselector(‘input’)[0] for the first form input). You can use this extracted data which is now saved to append to the page. There’s something called bubbling, basically if you have 3 onclicks, one in the section, one in a div, and another somewhere else in the body. When you click the one furthest down it will run, but then the 2nd one will also run, and then the one in the section. It will keep moving up the chain cause technically you are clicking on the section which does contain an onclick for a paragraph element. Include the (e) and then you can code, e.stopPropagation. Event delegation – may be useful for when some element is not on the page at times when the eventListener was added. The workaround is to attach the eventListener to a parent element (which of course you’ve already saved to variable). Now, in the case of removing <li> like from a grocery list, attach to the <ul> which will always be there. We can then listen for clicks on <ul> but using console.log(e) you can find something called the target, in this case is showing <li> which is great. Now we can write e.target.remove(). In the case where there may be spacing or padding or other elements in the <ul> we can avoid accidentally removing wrong thing by writing. console.dir(e.target) you will see nodeName = “LI” signifying the node attribute as being LI. Now, we can write a condition to only remove <li> nested in the <ul> with the following condition. e.target.nodeName === ‘LI’ && e.target.remove() End of day: Finally can add some interactivity to a site, when a user does some action, I can manipulate the DOM. Day #8 – Asycn JavaScript Hours spent: 5 hours Not going in detail into asynchronous JavaScript according to the course. Just high-level view of what’s going on. Callstack, the code is run, removed from the most recent thing, saved in a callback queue if it is asynchronous and loaded based on onclick, timeout or whatever else. It’s basically the sequence of how your code runs, you can debug and see using the developer tool, under the source-tab. You can click a line which will add a break (meaning no code after the break will run) and you can go step by step to find out where if anywhere the code need repairing. JS is single threaded, only can read one line at a time. Cannot multi-task. This does not mean that if you have a timeout function that your next line in JS stops until 3 seconds is over. The browser is written is C++ which takes reign and will help with the use of WebAPIs. It will pass off requests, timeout, sending info to a database. Once the browser finishes those tasks, they are returned and pushed to the queue and then back to your callstack. See latentflip.com for visualization. Callback hell – only after the first thing is finished can the second thing happen. They get very nested and crazy but are necessary, if you’re working with webAPI or database requests you want multiple paths for both success and failure. Didn’t fully understand, but the next video was the promise syntax which was suppose to promise a better future. Promise only requires one parameter, whereas before we had callbacks for both success and failure. The promise has 3 states, pending, resolved or rejected. A promise is an object which you can attach callbacks instead of passing callbacks into a function. .then to write a success callback and .catch to return a failure callback. fakeRequestPromise(‘yelp.com/api/coffee/page1’) .then(() => { console.log(“IT WORKED!!!!!! (page1)”) fakeRequestPromise(‘yelp.com/api/coffee/page2’) .then(() => { console.log(“IT WORKED!!!!!! (page2)”) fakeRequestPromise(‘yelp.com/api/coffee/page3’) .then(() => { console.log(“IT WORKED!!!!!! (page3)”) }) .catch(() => { console.log(“OH NO, ERROR!!! (page3)”) }) }) .catch(() => { console.log(“OH NO, ERROR!!! (page2)”) }) }) .catch(() => { console.log(“OH NO, ERROR!!! (page1)”) }) This is not much better than the callback hell. But with promises we can simplify further, we can add a return and only one catch for all the nested fakeRequestPromise. Promise chaining, dependent asynchronous actions where 3 will only happen if 2 happens which only happens if 1 happens, if there’s a failure anywhere, then it will skip to the catch. Hope I never have to use callback as promises were actually much easier to understand the way it’s laid out here. fakeRequestPromise(‘yelp.com/api/coffee/page1’) .then((data) => { console.log(“IT WORKED!!!!!! (page1)”) console.log(data) return fakeRequestPromise(‘yelp.com/api/coffee/page2’) }) .then((data) => { console.log(“IT WORKED!!!!!! (page2)”) console.log(data) return fakeRequestPromise(‘yelp.com/api/coffee/page3’) }) .then((data) => { console.log(“IT WORKED!!!!!! (page3)”) console.log(data) }) .catch((err) => { console.log(“OH NO, A REQUEST FAILED!!!”) console.log(err) }) The two missing pieces aysnc and the await keyword. Adding async before a function converts the function automatically to a promise. const sing = async () => {return ‘la la la’} sing ().then ((data) => { console.log(“promise resolved:”, data}) To reject a promise, you can throw an error. Throwing an error can be as simple as syntax error, but you can throw your own error. This looks like,. const sing = async () => { throw new Error(“probem”) //you can also just write a string, throw “problem” return ‘la la la’ } sing ().then ((data) => { console.log(“promise resolved:”, data}) The await keyword. We can only use the await keyword inside of functions declared with async. Await will pause the execution of the function, waiting for a promise to be resolved. Your code will work in a way where the next sequence will only run once the first has been resolved. How can we handle rejection with the await keyword? Try and catch. Try{ let data = await previousFunction(‘page/1’) console.log(data) } catch (e){ console.log(“error is:”, e) } APIs, AJAX and JSON. When we discuss APIs we really mean WEB APIs which give us access to an endpoint. Companies create APIs so we can access something, like Twitter APIs allow us to retrieve posts, create automation, analyze. Weather API gives us the data for weather. We can extra this data and create widget or whatever on our end. APIs are typically in JSON (really AJAX where x is XML, but this is rarely used AJAJ but still referred to as AJAX). It’s a string of text, but we can convert into JS rather easily with const parsedData = JSON.parse(data) where data is a variable created storing the value of the API. We can now type parsedData.price (e.g. to pull the bitcoin price from a bitcoin API). fetch(‘API.com’) and it will deliver a promise. Day #9 – Web APIs Hours spent: 2 Postman application download for APIs used for looking at data, tweaking the request we are sending, inspecting the responses. Body of a API response is the content, http status code 200 is valid API recognized and live. Headers are key value pairs, they are like the meta deta of for the response or the request. Each API is different and you have to read their documentation to understand how to use. For TVmaze you’ll see query string. For Icanhazdadjoke you’ll see you’ll need to set parameter to accept header of application/json. Something XHR request, skipped over as it was the old version. Now there’s fetch which is newer. You can use .then and .catch but the thing is it doesn’t actually pass on the data. It will just resolve or reject your request if it receive the header (not all the data is passed through). But you can chain on and return a .json request which is another promise. But for some reason (not fully understood) you can write a second .then statement and print the data. *note* fetch is not perfect – libraries like axios exist. You can write a cleaner fetch with an async function: const fetchBitcoinPrice = async () => { const res = await fetch (bitcoinAPI.com/example) const data = await res.json (); console.log(data.ticker.price) } Also note, you can put all that code in a try, and have a fallback with a catch to deal with errors. Axios library – you can either download or put the script (ideally in the <head> – just needs to be higher than your .js file so it’s read first) Axios.get(bitcoin.com/exampleAPI) in console, you’ll see it’s a promise that has already been parsed. All you have to do is write your single .then (res => { console.log (res.data.ticker.price) } You will know the data.ticker.price by looking at what’s returned in the developer console for that API. Setting headers in axios, with the ,get you can pass through a second arguement, .get(api, {headers :{Accept: ‘application/json’}} You can even set up the parameter as a constant and pass in the variableName if you’d like. Day #10 – Terminal Hours spent: Downloaded Git Bash Navigating the terminal (use tab to autocomplete typing): PWD – current directory LS – List folders CD – control which directory you want to go CD .. – Back tab mkdir + newFolderName – will make new folder, you can also create multiple folders at once with space. You can navigate relative to where you are, for example if you’re in users you can type userName/Downloads, or can use absolute like CD /Users/userName/Downloads. Notice the slash in the front for absolute. Shortcut would be CD / which takes you to root directory. You can also chain navigation cd ../../nameOfFolder, which will take you back two and up one to the new folder, but it’s relative to where you are. You can find manual (man ls) which gives you sorting options (flags) which we can pass in in ls to organize (sort, reverse, filter by size etc). The touch command allows you to create files within a folder. You can create touch index.html app.js style.css and you created 3 files in that folder. Removing files and folders – rm app.css *completely gone* it’s deleted permanently and there’s no recycling bin. rmdir will delete empty directory. rm – rf will delete the entire directory. Intro to node.js and installing node.js to run outside the browser. End of day: I am stopping my JavaScript journey for now. I believe I have the necessary knowledge to go make some tweaks on the sites I own with knowledge of events and introduction to the DOM. The JS course was getting into the backend with Express, NODEjs and introduction to database which for me at this point is not necessary.