Skip to content

Latest commit

 

History

History
271 lines (197 loc) · 6.7 KB

Day 5 .md

File metadata and controls

271 lines (197 loc) · 6.7 KB

💎 Day 5 💎



Data Fetching & Promises 🎯🚀


👉 see that 👈

URLs point to resources on the web APIs (Application Programming Interface) services that are exposing a whole bunch of data at acertin URLs**,** provide URLs that point at data we care about


Promise: 💫🌌

Object represents the eventual completion (or failure) of an asynchronous operation and its resulting value (represent a value that we don’t have yet)

Promises can be in 3 possible states:🔮🫧

  1. pending: still waiting for the value, hang tight
  2. fulfilled (aka resolved): finally got the value, all done
  3. rejected: sorry couldn't get the value, all done

await: ✨⚡️

await lets us tell JS to stop and wait for an asynchronous operation to finish

let response = await fetch("https://dog.ceo/api/breed/hound/list");
console.log(response);

.json() 💻🔥

It's body contains the data we care about

But we have to read the body somehow

💡 Note

json() is async fun


// Calling the .json() method on the response parses its body as a JSON object
let r = await response.json()


Destructuring Data ⏳🤔

Destructuring is a fancy way of declaring multiple variables at once

By "extracting" values from an object with their property names

const spices = [{name:"Sarah", nickname:"queen"}]
let {name, nickname} = spices[0];

Use it with array ✨☄️

const [one, tow ] = [1,2]

// We can ignore the values in the array we don't need
const [,,melB] = spices;

// We can use ... to collect remaining values
 const [babySpice, ...adultSpices] = spices;

Exercise: 👩🏻‍💻🤔

/*
	In your Doggo Fetch file, follow TODO 2 to complete the getBreedFromURL 
	function with destructuring
	
	The string method .split() will be useful it returns an array of substrings
	 by splitting a string at a certain character: 
*/
let part = "https://images.dog.ceo/breeds/poodle-standard/n02113799_2280.jpg"
         .split("/") // parts of url
let name =  part[4] // the name
let removed = name.split("-")
let joinedName = removed.join(" ")
let finalName = joinedName.trim() // to remove the white spaces if the name 
																	// just one word


async 🔥💫

Exercise: ✏️📝

/*
In your Doggo Fetch file, follow TODO 3 to fill in the async function body

Use what we've learned about how to fetch, parse, and extract the data we need
*/
async function fetchMessage(url) {
        const response = await fetch(url);  // Fetch the resource at the given URL
        const {message} = await response.json(); // Parse the response as JSON & remember its 'message' value
        return message;
    }

createElement() 🧐🪩

In an HTML document, the document.createElement() method creates the HTML element specified by tagName

const button = document.createElement("button")

appendChild() 🎆🌟

The appendChild() method of the Node interface adds a node to the end of the list of children of a specified parent node.

options.appendChild(button)


Modules 🍄🍃

Modules let us split big codebases across multiple files

<script type="module">
    //...
</script>

// JS modules work differently from JS scripts

Module scope: 🎀💎

💡 Note:

We can't access variables and function in the web console



Debugging: ✏️📋

We can console.log() (or .warn() or .error()) is one way to understand what's happening when your program runs

function whyIsntThisWorking(input) {
    console.log("Well at least we got this far");
    console.log(input);
    return thingThatDoesntWork(input);
}

You can also use the browser's debugger to pause JS and inspect what's happening
function whyIsntThisWorking(input) {
    debugger;
    return thingThatDoesntWork(input);
}

The debugger statement creates a breakpoint where JS will pause and let you look around



💡 Notes:

  1. trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string.
  2. In JS we can creat any element we want to appeare in HTML page.


GSG Task 🔥🌠:

Task discription

My solution



Coding Exercises for challenges: 🔥💪

  1. Reuse JavaScript Code Using import My solution:
  import {uppercaseString, lowercaseString} from './string_functions.js'
// Only change code above this line

uppercaseString("hello");
lowercaseString("WORLD!");
  1. Use * to Import Everything from a File My solution:
import * as stringFunctions from "./string_functions.js";
// Only change code above this line

stringFunctions.uppercaseString("hello");
stringFunctions.lowercaseString("WORLD!");
  1. Create an Export Fallback with export default My solution:
export default  function subtract(x, y) {
  return x - y;
}
  1. Import a Default Export My solution:
import subtract from './math_functions.js'
// Only change code above this line

subtract(7,4);
  1. Create a JavaScript Promise My solution:
const  makeServerRequest = new Promise((resolve, reject) => {

});


Problem Solving: 💪🚀

  1. Leap Years My solution:
function isLeapYear(year) {
  return  year % 400 === 0 || (year % 100 !== 0 && year % 4 === 0)  ;
}
  1. Detect Pangram My solution:
function isPangram(string) {
  const lowercaseString = string.toLowerCase();
  const uniqueLetters = new Set(lowercaseString.match(/[a-z]/g));
  return uniqueLetters.size === 26;
}