ECS6+ Flashcards

1
Q

Como criar templates?

A
Utilizando `${}`. Ex:
let word1 = 'Paulo';
let word2 = 'Mulotto';
const fullName = `${word1} ${word2}`
let num1 = 2;
let num2 = 3;
const sum= `${num1  + num2}`;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Como desestruturar um objeto?

A
const player = {
  name: 'Lebron James',
  club: 'LA Lakers',
  address: {
    city: 'Los Angeles'
  }
};

// console.log( player.address.city );

const { name, club, address: { city } } = player;

// console.log(${name} plays for ${club});

console.log(${name} lives in ${city});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Objetos Literais

A
function addressMaker(city, state) {
    let newAdress = {city, state};
    console.log(newAdress);
    // É igual a:
    // newAdress = {city:city, state:state};
console.log(newAdress); }

addressMaker(‘Austin’, ‘Texas’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Criando for loops

A
let incomes = [62000, 67000, 75000];
let total = 0;

for (const income of incomes) {
console.log(income);
total += income;
}

let fullName = “Dylan Coding God Israel”;

for (const char of fullName) {
console.log(char);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

// Challenge - For Of Loop

// Using the For of Loop, iterate through the array and print into the console, a message like:
// Tom lives in Lisbon
const students = [ 
    { name: "John", city: "New York" },
    { name: "Peter", city: "Paris"},
    { name: "Kate", city: "Sidney" }
]
A
const students = [ 
    { name: "John", city: "New York" },
    { name: "Peter", city: "Paris"},
    { name: "Kate", city: "Sidney" }
]
for (const person of students) {
    let {name, city} = person;
    console.log(`${name} lives in ${city}`);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How build a new copy of an structure like an array?

A

Using spread: let copy = [ …name_array ]

let contacts = [“Mary”, “Joel”, “Danny”];

let personalFriends = [ …contacts ];

contacts. push(“John”);
console. log(personalFriends);

//this also works
let personalFriends = [ "David", ...contacts, "Lily" ];

It is also possible with objects:

let person = {
    name: "Adam",
    age: 25,
    city: "Manchester"
}
let employee = {
    ...person,
    salary: 50000,
    position: "Software Developer"
}

console.log(employee);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q
/*
    **** Challenge ****
Imagine you are going out to do some grocery shopping.
So you have an array called shoppingList with all the products you want to buy.

Now that you are inside of the shop, you have a basket with all the products from your list, but you want to add a few more.

Create a new array called shoppingBasket, that will be a copy of the shoppingList array, and add some new products into it. 

*/

const shoppingList = [“eggs”, “milk”, “butter”];

A

const shoppingBasket = [ …shoppingList, “bread”, “pasta”];

console.log(shoppingBasket);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Rest Operator

A

Irá pegar todos os argumentos (args) enviados para a função e transformar numa lista:

function add(…nums) {

console.log(nums); }

add(4, 5, 7, 8, 12)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Arrow Function

A
//function declaration
function breakfastMenu() {
    return "I'm going to scrambled eggs for breakfast";
}
//anonymous function
const lunchMenu = function() {
    return "I'm going to eat pizza for lunch";
}
// const + nome da função = (parâmetros,...) => { função }
const dinnerMenu = (food) => {
    return `I'm going to eat a ${food} for dinner`;
}

console.log( dinnerMenu(“chicken salad”) );

// para um único parâmetro:
const dinnerMenu = food => `I'm going to eat a ${food} for dinner`;

console.log( dinnerMenu(“chicken salad”) );

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Default values in arrow functions

A
const leadSinger = (artist = "someone") => {
    console.log(`${artist} is the lead singer of Cold Play`);
}

leadSinger();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q
/*
**** Challenge *****

Create a function that receives a parameter of food.
If your parameter food is going to have a value of “milk”
the function should print into the console the following:

“I’m going to buy milk from the grocery shop”

But if you dont pass a value to your parameter food, it should print
“I’m going to buy something from the grocery shop”

*/

A
const getFood = (food="something") => {return `I'm going to buy ${food} from the grocery shop `};
console.log(getFood("milk"));
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

includes

A

let numArray = [1,2,3,4,5];

console.log(numArray.includes(2))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Import & Export

A
// exemple.js
export const data = [1,2,3];
// index.js
import { data } from './example.js';
let updatedData = data;

updatedData.push(5)
console.log(updatedData);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Challenge

Inside of the file data.js, create a function add, that will receive 2 numbers and return the sum of them.
Make sure to export this function.

  • Import the function add, into the index.js file
  • Create a variable result, that will hold the result of the function add when you call it and pass 2 numbers into it.
  • print into the console the value of the variable result;
A
//data.js
export const add = (num1, num2) => {
    return num1 + num2;
}
//index.js
import { add } from './data.js';

let result = add(3, 2);

console.log(result);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Classes

A
// animal.js
export class Animal {
    constructor(type, legs) {
        this.type = type;
        this.legs = legs;
    }
makeNoise(sound = 'Loud Noise') {
    console.log(sound);
}
    get metaData() {
        return `Type: ${this.type}, Legs: ${this.legs}`;
    }
    static return10() {
        return 10;
    }
}
export class Cat extends Animal {
    makeNoise(sound = "meow") {
        console.log(sound);
    }
}
//index.js
import { Animal, Cat } from './animal.js';

let cat = new Cat(‘Cat’, 4);

cat. makeNoise();
console. log(cat.legs);
console. log(cat.metaData);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Classes Challenge:

Create a class Player with the following:

  • Add a Name and Country properties
  • Add a function that when it runs should print into the console (“Messi was born in Argentina”);
  • Make sure to adapt this function to receive dynamic Names and Clubs.

Create a Subclass called TennisPlayer that extends from the class Player

  • Add a new property Age.
  • Add a function that when it runs should print into the console something similar (“Rafael Nadal is 34 years old and knows how to play Tennis”);
  • Make sure the Name and Age are dynamic.
A
//player.js
export class Player {
    constructor(name, country) {
        this.name = name;
        this.country = country;
    }
isBorn() {
    return `${this.name} was born in ${this.country}`
} }
export class TennisPlayer extends Player {
    constructor (name, country, age) {
        super(name, country);
        this.age = age;
}

getDesc() {
    return `${this.name} is ${this.age} years old and knows how to play Tennis`
} }
//index.js
import { Player, TennisPlayer } from './player.js'

let p = new Player(‘Messi’, ‘Argentina’);
let pt = new TennisPlayer(‘Messi’, ‘Argentina’, 28);
console.log(p.isBorn());
console.log(pt.getDesc());

17
Q

Promeses

A

// Promises

const buyFlightTicket = () => {
    return new Promise( (resolve, reject) => {
        setTimeout( () => {
            const error = true;
            if( error ) {
                reject("Sorry your payment was not successful")
            } else {
                resolve("Thank you, your payment was successful");
            }
        }, 3000)
    })
}

buyFlightTicket()
.then( (success) => console.log(success))
.catch( (error) => console.log(error) );

18
Q

/**

  • Promises - Challenge
  • Create a promise that returns some user data and throws an error when not found.
  • Log the user data when listening to the promise as well as log the error.
  • Docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
  • /
A

/**

  • Promises - Challenge
  • Create a promise that returns some user data and throws an error when not found.
  • Log the user data when listening to the promise as well as log the error.
  • Docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
  • /
const user = {
    name: 'Paulo',
    age: 28,
}
const getUserData = (attr) => {
    return new Promise( (resolve,reject) => {
        if  (attr in user) {
            resolve(user[attr])
        } else {
            reject('Atributo não encontrado')
        }
    })
}

getUserData(“aeadv”)
.then( (success) => console.log(success))
.catch( (error) => console.log(error));

getUserData(“name”)
.then( (success) => console.log(success))
.catch( (error) => console.log(error));

19
Q

fetch

A

/**

  • Fetch
  • RESTFul API - https://jsonplaceholder.typicode.com/
  • Docs - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
  • /
// fetch('https://jsonplaceholder.typicode.com/comments/1')
//     .then(response => response.json())
//     .then(data => console.log(data))
fetch('https://jsonplaceholder.typicode.com/comments', {
        method: "POST",
        body: JSON.stringify({
            postId: 1,
            name: 'Dylan',
            email: 'dylansemail310@gmail.com',
            body: 'That was dope!'
        })
    })
    .then(response => response.json())
    .then(data => console.log(data))
20
Q

/**

  • Fetch - Challenge
  • GET the first comments value ‘https://jsonplaceholder.typicode.com/comments/1’ and log its value.
  • POST a new comment using ‘https://jsonplaceholder.typicode.com/comments’ and log its value.
  • RESTFul API Guide - https://jsonplaceholder.typicode.com/guide.html
  • Docs - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
  • /
A

fetch(‘https://jsonplaceholder.typicode.com/comments/1’)
.then(response => response.json())
.then((data) => console.log(data))

fetch('https://jsonplaceholder.typicode.com/comments', {
    method: "POST",
    body: JSON.stringify({
            name: 'Comment 105',
            email: 'paulo@gmail.com',
            body: 'Dopes comment in the game',
            postId: 1
        }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})
    .then(response => response.json())
    .then(data => console.log(data))
21
Q

Async & await

A

const photos = [];

async function photoUpload() {
    let uploadStatus = new Promise( (resolve, reject) => {
        setTimeout( () => {
            photos.push("Profile Pic");
            resolve("Photo Uploaded")
        }, 3000)
    })
    let result = await uploadStatus;
console.log(result);
console.log(photos.length); }

photoUpload().catch(error => console.log(error));

22
Q

//Challenge - Async & Await

//Print on the console a random joke from the Chuck Norris API using Fetch and Async and Await

const apiUrl = “https://api.chucknorris.io/jokes/random”;

A

const apiUrl = “https://api.chucknorris.io/jokes/random”;

async function randomJoke(apiUrl) {
    let response = await fetch(apiUrl);    
    let data = await response.json();
console.log(data) }

randomJoke(apiUrl).catch(error => console.log(error));