28 |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/08-Behind-the-Scenes/hoisting_tdz.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | /*console.log(me);
3 | console.log(job);
4 | console.log(year);
5 |
6 | var me = "Jonas";
7 | let job = "teacher";
8 | const year = 1991;
9 | */
10 |
11 | //Function
12 | //Output 5
13 | console.log(addDecl(2, 3));
14 | //Output 'Uncaught ReferenceError: Cannot access 'addExpr' before initialization'
15 | //console.log(addExpr(2 + 3));
16 | //console.log(addArrow(2 + 3));
17 |
18 | function addDecl(a, b) {
19 | return a + b;
20 | }
21 |
22 | const addExpr = function (a, b) {
23 | return a + b;
24 | };
25 |
26 | const addArrow = (a, b) => a + b;
27 | //numProducts is undifined because of Hoisting and it will be false
28 | //Conclusion just dont use var to declare variables
29 | //Declare variables at the top of your code.
30 | //Declare function before and then call them
31 | if (!numProducts) {
32 | deleteShoppingCart();
33 | }
34 |
35 | var numProducts = 10;
36 | function deleteShoppingCart() {
37 | console.log("All products deleted");
38 | }
39 |
40 | // var variables will create a property on the window object
41 | var x = 1;
42 | //Let and const will not be visible on the window object
43 | let y = 2;
44 | const z = 3;
45 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/16_looping_arrays_breaking_and_continuing.js:
--------------------------------------------------------------------------------
1 | const jonas = [
2 | 'Jonas',
3 | 'Schmedtmann',
4 | 2037-1991,
5 | 'teacher',
6 | ['Michael', 'Peter', 'Steven'],
7 | true
8 | ];
9 |
10 | const types = [];
11 |
12 | for (let i = 0;i < jonas.length; i++) {
13 | // Reading from jonas array
14 | console.log(jonas[i], typeof jonas[i]);
15 |
16 | // Filling types array
17 | types[i] = typeof jonas [i]
18 | }
19 |
20 | console.log(types);
21 |
22 | const years = [1991, 2007, 1969, 2020];
23 | const ages = [];
24 |
25 | for (let i=0; i< years.length; i++) {
26 | ages.push(2037 - years[i]);
27 | }
28 | console.log(ages);
29 |
30 | // continue and break
31 | console.log('------ ONLY STRINGS ----')
32 | for (let i = 0;i < jonas.length; i++) {
33 | // Reading from jonas array
34 | if( typeof jonas[i] !== 'string') continue;
35 | console.log(jonas[i], typeof jonas[i]);
36 |
37 | }
38 |
39 |
40 | console.log('------ BREAK WITH NUMBER ----')
41 | for (let i = 0;i < jonas.length; i++) {
42 | // Reading from jonas array
43 | if( typeof jonas[i] === 'number') break;
44 | console.log(jonas[i], typeof jonas[i]);
45 |
46 | }
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/12_dot_vs_bracket_notation.js:
--------------------------------------------------------------------------------
1 | // In dot notation we have to use the real property name and not the computed one
2 | const jonas = {
3 | firstName: 'Jonas',
4 | lastName: 'Schmedtmann',
5 | age: 2037-1991,
6 | job: 'teacher',
7 | friends: ['Michael', 'Peter', 'Steven']
8 | };
9 |
10 | console.log(jonas);
11 | console.log(jonas.lastName);
12 | console.log(jonas['lastName']);
13 |
14 | const nameKey = 'Name';
15 |
16 | console.log(jonas['first' + nameKey]);
17 | console.log(jonas['last' + nameKey]);
18 |
19 | const interestedIn = prompt(' What do you want to know about Jonas? Choose between firstName, lastName, age, job and friends');
20 |
21 | if (jonas[interestedIn]) {
22 | console.log(jonas[interestedIn]);
23 | } else {
24 | console.log('Wrong request! Choose between firstName, lastName, age, job, and friends')
25 |
26 | }
27 |
28 | jonas.location = 'Portugal';
29 | jonas['twitter'] = '@jonasschmedtman';
30 | console.log(jonas);
31 |
32 | //Challenge
33 | // "Jonas has 3 friends, and his best friend is called Michael"
34 |
35 |
36 | console.log(`${jonas.firstName} has ${jonas.friends.length} friends and his best friend is called ${jonas.friends[0]}`)
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/20_coding_challenge_4.js:
--------------------------------------------------------------------------------
1 | /*Coding Challenge #4
2 | Steven wants to build a very simple tip calculator for whenever he goes eating in a
3 | restaurant. In his country, it's usual to tip 15% if the bill value is between 50 and
4 | 300. If the value is different, the tip is 20%.
5 | Your tasks:
6 | 1. Calculate the tip, depending on the bill value. Create a variable called 'tip' for
7 | this. It's not allowed to use an if/else statement 😅 (If it's easier for you, you can
8 | start with an if/else statement, and then try to convert it to a ternary
9 | operator!)
10 | 2. Print a string to the console containing the bill value, the tip, and the final value
11 | (bill + tip). Example: “The bill was 275, the tip was 41.25, and the total value
12 | 316.25”
13 | Test data:
14 | § Data 1: Test for bill values 275, 40 and 430
15 | Hints:
16 | § To calculate 20% of a value, simply multiply it by 20/100 = 0.2
17 | § Value X is between 50 and 300, if it's >= 50 && <= 300 😉
18 | GOOD LUCK 😀
19 | */
20 |
21 |
22 |
23 | const bill = 275;
24 | const tip = bill >= 50 && bill <= 300 ? bill * 0.15: bill * 0.2;
25 | console.log(`The bill was ${bill}, the tip was ${tip}, and the total value
26 | ${bill + tip}`) ;
27 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/09_basic_array_operations.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | // Friends array
4 | const friends = ['Michael', 'Steven', 'Peter'];
5 |
6 | // Adds an element to the end of the array
7 | const friendsArrayLength = friends.push('Jay');
8 | console.log('Friends', friends);
9 | console.log('Friends array length', friendsArrayLength);
10 |
11 | // Add element to the beginning of the array
12 | friends.unshift('John');
13 | console.log(friends);
14 |
15 | // Remove last element of the array
16 | const popped = friends.pop();
17 | console.log('Length of friends array after the last element is being removed', popped)
18 | console.log('Friends', friends);
19 |
20 | //Remove the first element of the array
21 | friends.shift();
22 | console.log('Friends', friends);
23 |
24 | // Get index of an element in an array
25 | console.log('Index of Steven in the array', friends.indexOf('Steven'));
26 | console.log('Index of Bob in the array', friends.indexOf('Bob'));
27 |
28 | // Check if an element in array or not - strict check
29 | console.log('Is Steven in friends array?', friends.includes('Steven'));
30 | console.log('Is Bob in friends array?', friends.includes('Bob'));
31 |
32 | if(friends.includes('Steven')) {
33 | console.log('You have a friends called Steven');
34 | }
--------------------------------------------------------------------------------
/09-Data-Structures-Operators/nullish_coalescing_operator.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const restaurant = {
4 | name: 'Classico Italiano',
5 | location: 'Via Angelo Tavanti 23, Firenze, Italy',
6 | categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
7 | starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
8 | mainMenu: ['Pizza', 'Pasta', 'Risotto'],
9 |
10 | order(starterIndex, mainIndex) {
11 | return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
12 | },
13 |
14 | orderDelivery({ starterIndex = 1, mainIndex = 0, time = '20:00', address }) {
15 | console.log(
16 | `Order received! ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]} will be delivered to ${address} at ${time}`
17 | );
18 | },
19 |
20 | orderPasta(ing1, ing2, ing3) {
21 | console.log(
22 | `Here is your declicious pasta with ${ing1}, ${ing2} and ${ing3}`
23 | );
24 | },
25 |
26 | orderPizza(mainIngredient, ...otherIngredients) {
27 | console.log(mainIngredient);
28 | console.log(otherIngredients);
29 | },
30 | };
31 |
32 | restaurant.numGuests = 0;
33 |
34 | const guests = restaurant.numGuests || 10;
35 | console.log(guests);
36 |
37 | //Nullish: null and undefined (NOT 0 or "")
38 | const guestCorrect = restaurant.numGuests ?? 10;
39 | console.log(guestCorrect);
40 |
--------------------------------------------------------------------------------
/07-Dom-Events-Fundamentals-2/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | Modal window
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
I'm a modal window 😍
18 |
19 | Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
20 | tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
21 | veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
22 | commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
23 | velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
24 | occaecat cupidatat non proident, sunt in culpa qui officia deserunt
25 | mollit anim id est laborum.
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/17_switch_statement.js:
--------------------------------------------------------------------------------
1 | // Switch statement
2 |
3 | const day = 'monday';
4 |
5 | switch(day) {
6 | case "monday": // day === "monday"
7 | console.log("Plan my course structure");
8 | console.log("Go to coding meetup");
9 | break;
10 | case "tuesday":
11 | console.log("Prepare theory videos");
12 | break;
13 | case "wednesday":
14 | case "thursday":
15 | console.log("Write code examples");
16 | break;
17 | case "friday":
18 | console.log("Record videos");
19 | break;
20 | case "sunday":
21 | case "saturday":
22 | console.log("Enjoy the weekend :D");
23 | break;
24 | default:
25 | console.log("Not a valid day!");
26 | }
27 |
28 | // Replace the code above with an if/else statement
29 |
30 | if (day === "monday") {
31 | console.log("Plan my course structure");
32 | console.log("Go to coding meetup");
33 | } else if(day === "tuesday") {
34 | console.log("Prepare theory videos");
35 | } else if (day === "wednesday" || day === "thursday") {
36 | console.log("Write code examples");
37 | } else if (day === "friday") {
38 | console.log("Record videos");
39 | } else if (day === 'sunday' || day === 'saturday') {
40 | console.log("Enjoy the weekend :D");
41 | } else {
42 | console.log(`${day} is not a valid day!`);
43 | }
--------------------------------------------------------------------------------
/08-Behind-the-Scenes/script.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | function calcAge(birthYear) {
4 | const age = 2037 - birthYear;
5 | console.log(firstName);
6 | function printAge() {
7 | let output = `${firstName}, you are the ${age}, born in ${birthYear}`;
8 | console.log(output);
9 |
10 | if (birthYear >= 1981 && birthYear <= 1996) {
11 | var millenial = true;
12 | //Firstname is variable inside the scope so JS will use that variable intead of the one outside the scope(lookup on the scope chain is not needed)
13 | const firstName = "Steven";
14 | const str = `Oh, you are a millenial, ${firstName}`;
15 | console.log(str);
16 | //Function are block scoped and only is true for strict mode
17 | function add(a, b) {
18 | return a + b;
19 | }
20 | output = "NEW OUTPUT";
21 | }
22 | console.log(millenial);
23 | //add(2, 3);
24 | console.log(output);
25 | }
26 | printAge();
27 | return age;
28 | }
29 |
30 | //Global variable
31 | const firstName = "Jonas";
32 | /* After the call the function does not find the variable inside her scope
33 | then perform a lookups in the scope chain to find it.
34 | The parent scope of calcAge function is the global scope and the firstName is there.
35 | */
36 | calcAge(1991);
37 | //We cannot have access variable of the child scope
38 | //console.log(age);
39 | //printAge();
40 |
--------------------------------------------------------------------------------
/07-Pig-Game/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | Pig Game
9 |
10 |
11 |
12 |
13 |
Player 1
14 |
43
15 |
16 |
Current
17 |
0
18 |
19 |
20 |
21 |
Player 2
22 |
24
23 |
24 |
Current
25 |
0
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/08-Behind-the-Scenes/regular_vs_arrow_functions.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | //if we use var window.firstName will print "Matilda" and this is one more reason not to use var
3 | let firstName = "Matilda";
4 | //This is not a codeblock but an object literal
5 | const jonas = {
6 | firstName: "Jonas",
7 | year: 1991,
8 | calcAge: function () {
9 | console.log(this);
10 | console.log(2037 - this.year);
11 | //Regular function call this is undefined
12 | //const isMillenial = function () {
13 | // console.log(this.year >= 1981 && this.year <= 1996);
14 | //};
15 |
16 | //Solution, use the arrow function
17 |
18 | const isMillenial = () => {
19 | console.log(this);
20 | console.log(this.year >= 1981 && this.year <= 1996);
21 | };
22 |
23 | isMillenial();
24 | },
25 | // You should never ever use arrow function as a method
26 | greet: () => console.log(`Hey ${this.firstName}`),
27 | greetDecl: function () {
28 | console.log(this);
29 | console.log(`Hey ${this.firstName}`);
30 | },
31 | };
32 | // this.firstName will check automatically on the parent scope which is window.firstName
33 | jonas.greet();
34 | jonas.greetDecl();
35 | jonas.calcAge();
36 |
37 | //arguments keyword
38 | const addExpr = function (a, b) {
39 | console.log(arguments);
40 | return a + b;
41 | };
42 | addExpr(2, 5);
43 | var addArrow = (a, b) => {
44 | //arguments is not defined
45 | console.log(arguments);
46 | return a + b;
47 | };
48 |
49 | addArrow(2, 5, 8);
50 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/03_data_types.js:
--------------------------------------------------------------------------------
1 | let javascriptIsFun = true;
2 | console.log(javascriptIsFun);
3 | console.log(typeof true);
4 |
5 | console.log(typeof javascriptIsFun);
6 | console.log(typeof 23);
7 | console.log(typeof 'Jonas');
8 |
9 | javascriptIsFun = "YES!";
10 | console.log(typeof javascriptIsFun);
11 | console.log(javascriptIsFun);
12 |
13 | let john;
14 | console.log(typeof john);
15 | console.log(john);
16 |
17 | let mary = null;
18 | console.log(typeof mary);
19 | console.log(mary);
20 |
21 | let year;
22 | console.log(year);
23 | console.log(typeof year);
24 |
25 | year = 1991;
26 | console.log(typeof year);
27 |
28 | //Javascript bug that has not been solved for legacy reasons - returns object
29 | console.log(typeof null);
30 |
31 |
32 | // **************** NOTES: DATA TYPES *******************
33 |
34 | // In Javascript every value is either an object or a primitive value
35 |
36 | /* Primitive data types
37 | 1- Number: Floating point numbers - Used for decimal integers let age = 23
38 | 2- String: Sequence of characters - Used for text
39 | 3- Boolean: Logical type that can be only true or false - Used for taking decisions
40 | 4- Undefined: Value taken by a variable that is not yet defined (empty value)
41 | 5- Null: Also means empty value
42 | 6- Symbol: Value that is unique and can not be changed
43 | 7- BigInt: Larger integers than the number type can hold */
44 |
45 | // Javascript has dynamic typing: We do not have to manually define the data of the value stored in a variable. Instead, data types are determined automatically.
46 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/08_introduction_to_arrays.js:
--------------------------------------------------------------------------------
1 | // Introduction to Arrays
2 | 'use strict';
3 |
4 | const friend1 = 'Michael';
5 | const friend2 = 'Steven';
6 | const friend3 = 'Peter';
7 |
8 | const years = new Array(1991, 1984, 2008, 2020);
9 | console.log('Years array', years);
10 |
11 | const test = new Array('5');
12 | console.log('Type of', typeof test[0]);
13 | console.log('Array length', test.length);
14 |
15 | const friends = ['Michael', 'Steven', 'Peter'];
16 | console.log('Friends array', friends);
17 | console.log('Friend 1', friends[0]);
18 | console.log('Friend 2',friends[1]);
19 | console.log('Friend 3',friends[2]);
20 | console.log('Friends array length',friends.length);
21 |
22 | // Last element in array
23 | console.log('Last element in array', friends[friends.length - 1]);
24 |
25 | // Overwrite array elements
26 | friends[2] = 'Jay';
27 | console.log('Friends array updated', friends); // ['Michael', 'Steven', 'Jay']
28 |
29 | const jonas = ['Jonas', 'Schmedtmann', 2037 - 1991, 'teacher', friends];
30 | console.log('Jonas array', jonas);
31 | console.log('Jonas array length', jonas.length);
32 |
33 |
34 | // ********* Example ***********
35 |
36 | const calcAge = function(birthYear) {
37 | return 2037 - birthYear;
38 | }
39 |
40 | const y = [1990, 1967, 2002, 2010, 2018];
41 |
42 | // console.log('Calculate age', calcAge(y));
43 |
44 | const age1 = calcAge(y[0]);
45 | console.log('Age 1', age1);
46 | const age2 = calcAge(y[1]);
47 | console.log('Age 2', age2);
48 | const age3 = calcAge(y[2]);
49 |
50 | console.log('Age 3', age3);
51 |
52 | const ages = [age1, age2, age3];
53 | console.log('Ages', ages);
--------------------------------------------------------------------------------
/09-Data-Structures-Operators/destructuring_arrays.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | // Data needed for a later exercise
4 | const flights =
5 | '_Delayed_Departure;fao93766109;txl2133758440;11:25+_Arrival;bru0943384722;fao93766109;11:45+_Delayed_Arrival;hel7439299980;fao93766109;12:05+_Departure;fao93766109;lis2323639855;12:30';
6 |
7 | // Data needed for first part of the section
8 | const restaurant = {
9 | name: 'Classico Italiano',
10 | location: 'Via Angelo Tavanti 23, Firenze, Italy',
11 | categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
12 | starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
13 | mainMenu: ['Pizza', 'Pasta', 'Risotto'],
14 |
15 | order: function (starterIndex, mainIndex) {
16 | return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
17 | },
18 | };
19 |
20 | const arr = [2, 3, 4];
21 | const a = arr[0];
22 | const b = arr[1];
23 | const c = arr[2];
24 |
25 | const [x, y, z] = arr;
26 | console.log(x, y, z);
27 |
28 | let [main, , secondary] = restaurant.categories;
29 | const [first, , second] = restaurant.categories;
30 | console.log(first, second);
31 | //Switching variables
32 |
33 | //console.log(main, secondary);
34 | //const temp = main;
35 | //main = secondary;
36 | //secondary = temp;
37 | //console.log(main, secondary);
38 |
39 | [main, secondary] = [secondary, main];
40 | console.log(main, secondary);
41 | const [starter, mainCourse] = restaurant.order(2, 0);
42 | console.log(starter, mainCourse);
43 | const nested = [2, 4, [5, 6]];
44 | const [i, , j] = nested;
45 | console.log(i, j);
46 |
47 | const [t, , [v, m]] = nested;
48 | console.log(t, v, m);
49 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/14_coding_challenge_3.js:
--------------------------------------------------------------------------------
1 | /*Coding Challenge #3
2 | Let's go back to Mark and John comparing their BMIs! This time, let's use objects to
3 | implement the calculations! Remember: BMI = mass / height ** 2 = mass
4 | / (height * height) (mass in kg and height in meter)
5 | Your tasks:
6 | 1. For each of them, create an object with properties for their full name, mass, and
7 | height (Mark Miller and John Smith)
8 | 2. Create a 'calcBMI' method on each object to calculate the BMI (the same
9 | method on both objects). Store the BMI value to a property, and also return it
10 | from the method
11 | 3. Log to the console who has the higher BMI, together with the full name and the
12 | respective BMI. Example: "John's BMI (28.3) is higher than Mark's (23.9)!"
13 | Test data: Marks weights 78 kg and is 1.69 m tall. John weights 92 kg and is 1.95 m
14 | tall.
15 | GOOD LUCK 😀
16 | */
17 |
18 | const mark = {
19 | fullName: 'Mark Miller',
20 | mass: 78,
21 | height: 1.69,
22 | calcBMI: function (){
23 | this.BMI = this.mass / (this.height * this.height)
24 | return this.BMI;
25 | }
26 | };
27 |
28 | const john = {
29 | fullName: 'John Smith',
30 | mass: 92,
31 | height: 1.95,
32 | calcBMI: function (){
33 | this.BMI = this.mass / (this.height * this.height)
34 | return this.BMI;
35 | }
36 | };
37 |
38 | mark.calcBMI();
39 | john.calcBMI();
40 |
41 |
42 | if (mark.BMI > john.BMI) {
43 | console.log(`Mark's BMI (${mark.BMI}) is higher than John's (${john.BMI})!`)
44 | } else if( john.BMI > mark.BMI) {
45 | console.log(`John's BMI (${john.BMI}) is higher than Mark's (${mark.BMI})!`)
46 | }
47 |
--------------------------------------------------------------------------------
/07-Dom-Events-Fundamentals-2/style.css:
--------------------------------------------------------------------------------
1 | * {
2 | margin: 0;
3 | padding: 0;
4 | box-sizing: inherit;
5 | }
6 |
7 | html {
8 | font-size: 62.5%;
9 | box-sizing: border-box;
10 | }
11 |
12 | body {
13 | font-family: sans-serif;
14 | color: #333;
15 | line-height: 1.5;
16 | height: 100vh;
17 | position: relative;
18 | display: flex;
19 | align-items: flex-start;
20 | justify-content: center;
21 | background: linear-gradient(to top left, #28b487, #7dd56f);
22 | }
23 |
24 | .show-modal {
25 | font-size: 2rem;
26 | font-weight: 600;
27 | padding: 1.75rem 3.5rem;
28 | margin: 5rem 2rem;
29 | border: none;
30 | background-color: #fff;
31 | color: #444;
32 | border-radius: 10rem;
33 | cursor: pointer;
34 | }
35 |
36 | .close-modal {
37 | position: absolute;
38 | top: 1.2rem;
39 | right: 2rem;
40 | font-size: 5rem;
41 | color: #333;
42 | cursor: pointer;
43 | border: none;
44 | background: none;
45 | }
46 |
47 | h1 {
48 | font-size: 2.5rem;
49 | margin-bottom: 2rem;
50 | }
51 |
52 | p {
53 | font-size: 1.8rem;
54 | }
55 |
56 | /* -------------------------- */
57 | /* CLASSES TO MAKE MODAL WORK */
58 | .hidden {
59 | display: none;
60 | }
61 |
62 | .modal {
63 | position: absolute;
64 | top: 50%;
65 | left: 50%;
66 | transform: translate(-50%, -50%);
67 | width: 70%;
68 |
69 | background-color: white;
70 | padding: 6rem;
71 | border-radius: 5px;
72 | box-shadow: 0 3rem 5rem rgba(0, 0, 0, 0.3);
73 | z-index: 10;
74 | }
75 |
76 | .overlay {
77 | position: absolute;
78 | top: 0;
79 | left: 0;
80 | width: 100%;
81 | height: 100%;
82 | background-color: rgba(0, 0, 0, 0.6);
83 | backdrop-filter: blur(3px);
84 | z-index: 5;
85 | }
86 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/10_coding_challenge_2.js:
--------------------------------------------------------------------------------
1 | /* Coding Challenge #2
2 | Steven is still building his tip calculator, using the same rules as before: Tip 15% of
3 | the bill if the bill value is between 50 and 300, and if the value is different, the tip is
4 | 20%.
5 | Your tasks:
6 | 1. Write a function 'calcTip' that takes any bill value as an input and returns
7 | the corresponding tip, calculated based on the rules above (you can check out
8 | the code from first tip calculator challenge if you need to). Use the function
9 | type you like the most. Test the function using a bill value of 100
10 | 2. And now let's use arrays! So create an array 'bills' containing the test data
11 | below
12 | 3. Create an array 'tips' containing the tip value for each bill, calculated from
13 | the function you created before
14 | 4. Bonus: Create an array 'total' containing the total values, so the bill + tip
15 | Test data: 125, 555 and 44
16 | Hint: Remember that an array needs a value in each position, and that value can
17 | actually be the returned value of a function! So you can just call a function as array
18 | values (so don't store the tip values in separate variables first, but right in the new
19 | array) 😉
20 | GOOD LUCK
21 | */
22 |
23 |
24 | 'use strict';
25 |
26 | const bills = [125,55,44]
27 |
28 | const tips = new Array();
29 | const totals = new Array();
30 |
31 | function calcTip(bill) {
32 | if(bill>=50 && bill<=300) {
33 | tips.push(bill*0.15);
34 | totals.push(bill*0.15+bill);
35 | } else {
36 | tips.push(bill*0.2)
37 | totals.push(bill*0.2+bill)
38 | }
39 | }
40 |
41 | calcTip(bills[0]);
42 | calcTip(bills[1]);
43 | calcTip(bills[2]);
44 |
45 | console.log(bills,tips, totals);
46 |
--------------------------------------------------------------------------------
/09-Data-Structures-Operators/logical_assignment_operator.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const restaurant = {
4 | name: 'Classico Italiano',
5 | location: 'Via Angelo Tavanti 23, Firenze, Italy',
6 | categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
7 | starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
8 | mainMenu: ['Pizza', 'Pasta', 'Risotto'],
9 |
10 | order(starterIndex, mainIndex) {
11 | return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
12 | },
13 |
14 | orderDelivery({ starterIndex = 1, mainIndex = 0, time = '20:00', address }) {
15 | console.log(
16 | `Order received! ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]} will be delivered to ${address} at ${time}`
17 | );
18 | },
19 |
20 | orderPasta(ing1, ing2, ing3) {
21 | console.log(
22 | `Here is your declicious pasta with ${ing1}, ${ing2} and ${ing3}`
23 | );
24 | },
25 |
26 | orderPizza(mainIngredient, ...otherIngredients) {
27 | console.log(mainIngredient);
28 | console.log(otherIngredients);
29 | },
30 | };
31 |
32 | const rest1 = {
33 | name: 'Capri',
34 | numGuests: 0,
35 | };
36 |
37 | const rest2 = {
38 | name: 'La piazza',
39 | owner: 'Jasmin Guzina',
40 | };
41 |
42 | // Using the short circuiting OR Operator we add the property numGuests if there is not presnt in the object
43 | //rest1.numGuests = rest1.numGuests || 10;
44 | //rest2.numGuests = rest2.numGuests || 10;
45 |
46 | //rest1.numGuests ||= 10; if we use or we will modify the numGuests prperty which is not our goal, to avoid this we use
47 | // Nullish assignment operator (null or undefined)
48 | rest1.numGuests ??= 10;
49 | rest2.numGuests ||= 10;
50 | //AND assignment operator assign a value to a variable is it is currently truthy
51 | rest1.owner &&= '';
52 | rest2.owner &&= '';
53 |
54 | console.log(rest1);
55 | console.log(rest2);
56 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/16_coding_challenge_3.js:
--------------------------------------------------------------------------------
1 | /*
2 | Coding Challenge #3
3 | There are two gymnastics teams, Dolphins and Koalas. They compete against each
4 | other 3 times. The winner with the highest average score wins a trophy!
5 | Your tasks:
6 | 1. Calculate the average score for each team, using the test data below
7 | 2. Compare the team's average scores to determine the winner of the competition,
8 | and print it to the console. Don't forget that there can be a draw, so test for that
9 | as well (draw means they have the same average score)
10 | 3. Bonus 1: Include a requirement for a minimum score of 100. With this rule, a
11 | team only wins if it has a higher score than the other team, and the same time a
12 | score of at least 100 points. Hint: Use a logical operator to test for minimum
13 | score, as well as multiple else-if blocks �
14 | 4. Bonus 2: Minimum score also applies to a draw! So a draw only happens when
15 | both teams have the same score and both have a score greater or equal 100
16 | points. Otherwise, no team wins the trophy
17 | Test data:
18 | § Data 1: Dolphins score 96, 108 and 89. Koalas score 88, 91 and 110
19 | § Data Bonus 1: Dolphins score 97, 112 and 101. Koalas score 109, 95 and 123
20 | § Data Bonus 2: Dolphins score 97, 112 and 101. Koalas score 109, 95 and 106
21 | GOOD LUCK �
22 | */
23 |
24 | const dolphinScore_1 = 97;
25 | const dolphinScore_2 = 112;
26 | const dolphinScore_3 = 101;
27 |
28 | const koalasScore_1 = 109;
29 | const koalasScore_2 = 95;
30 | const koalasScore_3 = 106;
31 |
32 | const dolphinAverage = (dolphinScore_1 + dolphinScore_2 + dolphinScore_3)/3;
33 | const koalasAverage = (koalasScore_1 + koalasScore_2 + koalasScore_3)/3;
34 |
35 | if( dolphinAverage > koalasAverage && dolphinAverage >= 100) {
36 | console.log(`The winner is Dolphins team`);
37 | } else if (koalasAverage > dolphinAverage && koalasAverage >= 100) {
38 | console.log(`The winner is Koalas team`);
39 | } else if(koalasAverage === dolphinAverage) {
40 | console.log('It is draw')
41 | }
--------------------------------------------------------------------------------
/09-Data-Structures-Operators/destructuring_objects.js:
--------------------------------------------------------------------------------
1 | // Data needed for first part of the section
2 |
3 | const restaurant = {
4 | name: 'Classico Italiano',
5 | location: 'Via Angelo Tavanti 23, Firenze, Italy',
6 | categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
7 | starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
8 | mainMenu: ['Pizza', 'Pasta', 'Risotto'],
9 | order: function (starterIndex, mainIndex) {
10 | return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
11 | },
12 | orderDelivery: function ({
13 | starterIndex = 1,
14 | mainIndex = 0,
15 | time = '20:00',
16 | address,
17 | }) {
18 | console.log(
19 | `Order received ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]}} will be delivered to ${address} at ${time}`
20 | );
21 | },
22 |
23 | openingHours: {
24 | thu: {
25 | open: 12,
26 | close: 22,
27 | },
28 | fri: {
29 | open: 11,
30 | close: 23,
31 | },
32 | sat: {
33 | open: 0, // Open 24 hours
34 | close: 24,
35 | },
36 | },
37 | };
38 |
39 | const { name, openingHours, categories } = restaurant;
40 | console.log(name, openingHours, categories);
41 |
42 | const {
43 | name: restaurantName,
44 | openingHours: hours,
45 | categories: tags,
46 | } = restaurant;
47 | console.log(restaurantName, hours, tags);
48 |
49 | //Default values
50 | const { menu = [], starterMenu: starters = [] } = restaurant;
51 | console.log(menu, starters);
52 |
53 | //Mutating variables
54 | let a = 111;
55 | let b = 999;
56 | const obj = { a: 23, b: 7, c: 14 };
57 | ({ a, b } = obj);
58 | console.log(a, b);
59 |
60 | //Nested Objects
61 | const {
62 | fri: { open: o, close: c },
63 | } = openingHours;
64 | console.log(o, c);
65 |
66 | restaurant.orderDelivery({
67 | time: '22:30',
68 | address: 'Via del Sole, 21',
69 | mainIndex: 2,
70 | starterIndex: 2,
71 | });
72 |
73 | restaurant.orderDelivery({
74 | address: 'Via del Sole, 21',
75 | starterIndex: 1,
76 | });
77 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/07_coding_challenge_1.js:
--------------------------------------------------------------------------------
1 | /*
2 | Coding Challenge 1
3 | Back to the two gymnastics teams, the Dolphins and the Koalas! There is a new
4 | gymnastics discipline, which works differently.
5 | Each team competes 3 times, and then the average of the 3 scores is calculated (so
6 | one average score per team).
7 | A team only wins if it has at least double the average score of the other team.
8 | Otherwise, no team wins!
9 | Your tasks:
10 | 1. Create an arrow function 'calcAverage' to calculate the average of 3 scores
11 | 2. Use the function to calculate the average for both teams
12 | 3. Create a function 'checkWinner' that takes the average score of each team
13 | as parameters ('avgDolphins' and 'avgKoalas'), and then logs the winner
14 | to the console, together with the victory points, according to the rule above.
15 | Example: "Koalas win (30 vs. 13)"
16 | 4. Use the 'checkWinner' function to determine the winner for both Data 1 and Data 2.
17 | 5. Ignore draws this time
18 | Test data:
19 | Data 1: Dolphins score 44, 23 and 71. Koalas score 65, 54 and 49
20 | Data 2: Dolphins score 85, 54 and 41. Koalas score 23, 34 and 27
21 | Hints:
22 | To calculate average of 3 values, add them all together and divide by 3
23 | To check if number A is at least double number B, check for A >= 2 * B.
24 | Apply this to the team's average scores 😉
25 | GOOD LUCK 😀*/
26 | 'use strict';
27 | const calcAverage = (score_1, score_2, score_3) => (score_1 + score_2 + score_3) / 3;
28 |
29 |
30 | const avgDolphins1 = calcAverage(44,23,71);
31 | const avgKoalas1 = calcAverage(65, 54, 49);
32 | const avgDolphins2 = calcAverage(85,54,41);
33 | const avgKoalas2 = calcAverage(23,34,27);
34 |
35 | function checkWinner(avgDolphins, avgKoalas) {
36 |
37 | if( avgDolphins >= 2*avgKoalas){
38 | console.log(`Delphins win (${avgDolphins} vs. ${avgKoalas})`) ;
39 | } else if( avgKoalas >= 2*avgDolphins){
40 | console.log(`Koalas win (${avgKoalas} vs. ${avgDolphins})`);
41 | } else {
42 | console.log('No team wins..');
43 | }
44 | }
45 |
46 | checkWinner(avgDolphins1, avgKoalas1);
47 | checkWinner(avgDolphins2, avgKoalas2);
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/19_coding_challenge_4.js:
--------------------------------------------------------------------------------
1 | /*Coding Challenge #4
2 | Let's improve Steven's tip calculator even more, this time using loops!
3 | Your tasks:
4 | 1. Create an array 'bills' containing all 10 test bill values
5 | 2. Create empty arrays for the tips and the totals ('tips' and 'totals')
6 | 3. Use the 'calcTip' function we wrote before (no need to repeat) to calculate
7 | tips and total values (bill + tip) for every bill value in the bills array. Use a for
8 | loop to perform the 10 calculations!
9 | Test data: 22, 295, 176, 440, 37, 105, 10, 1100, 86 and 52
10 | Hints: Call ‘calcTip ‘in the loop and use the push method to add values to the
11 | tips and totals arrays 😉
12 | Bonus:
13 | 4. Bonus: Write a function 'calcAverage' which takes an array called 'arr' as
14 | an argument. This function calculates the average of all numbers in the given
15 | array. This is a difficult challenge (we haven't done this before)! Here is how to
16 | solve it:
17 | 4.1. First, you will need to add up all values in the array. To do the addition,
18 | start by creating a variable 'sum' that starts at 0. Then loop over the
19 | array using a for loop. In each iteration, add the current value to the
20 | 'sum' variable. This way, by the end of the loop, you have all values
21 | added together
22 | 4.2. To calculate the average, divide the sum you calculated before by the
23 | length of the array (because that's the number of elements)
24 | 4.3. Call the function with the 'totals' array
25 | GOOD LUCK 😀
26 | */
27 |
28 | const bills = [22, 295, 176, 440, 37, 105, 10, 1100, 86, 52];
29 | const tips = [];
30 | const totals = [];
31 |
32 | function calcTip(bill) {
33 | if (bill >= 50 && bill <= 300) {
34 | tips.push(bill * 0.15);
35 | totals.push(bill * 0.15 + bill);
36 | } else {
37 | tips.push(bill * 0.2);
38 | totals.push(bill * 0.2 + bill);
39 | }
40 | }
41 |
42 | for (let i = 0; i < bills.length; i++) {
43 | calcTip(bills[i]);
44 | }
45 |
46 | console.log(bills, tips, totals);
47 |
48 | function calcAverage(arr) {
49 | let sum = 0;
50 | for (let i = 0; i < arr.length; i++) {
51 | sum = sum + arr[i];
52 | var average = sum / arr.length;
53 | }
54 | return average;
55 | }
56 |
57 | console.log(calcAverage(totals));
58 |
59 | const jas = 'dsdfd';
60 |
61 | const x = 23;
62 |
--------------------------------------------------------------------------------
/09-Data-Structures-Operators/short_circuiting.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const restaurant = {
4 | name: 'Classico Italiano',
5 | location: 'Via Angelo Tavanti 23, Firenze, Italy',
6 | categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
7 | starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
8 | mainMenu: ['Pizza', 'Pasta', 'Risotto'],
9 |
10 | order(starterIndex, mainIndex) {
11 | return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
12 | },
13 |
14 | orderDelivery({ starterIndex = 1, mainIndex = 0, time = '20:00', address }) {
15 | console.log(
16 | `Order received! ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]} will be delivered to ${address} at ${time}`
17 | );
18 | },
19 |
20 | orderPasta(ing1, ing2, ing3) {
21 | console.log(
22 | `Here is your declicious pasta with ${ing1}, ${ing2} and ${ing3}`
23 | );
24 | },
25 |
26 | orderPizza(mainIngredient, ...otherIngredients) {
27 | console.log(mainIngredient);
28 | console.log(otherIngredients);
29 | },
30 | };
31 |
32 | // Use any data type, return any data type, short-circuiting
33 | //Short circuiting OR operator means that if the first value is a truthy value it will immediately return the first value
34 | console.log(3 || 'Jonas');
35 | console.log('' || 'Jonas');
36 | console.log(true || 0);
37 | console.log(undefined || null);
38 |
39 | console.log(undefined || 0 || '' || 'Hello' || 23 || null);
40 |
41 | restaurant.numGuests = 0;
42 | const guests1 = restaurant.numGuests ? restaurant.numGuests : 10;
43 | console.log(guests1);
44 | const guests2 = restaurant.numGuests || 10;
45 | console.log(guests2);
46 |
47 | console.log('------ AND ------');
48 | //Short circuiting AND operator means that if the first value is a falsy value it will immediately return the first value without checking the other values
49 | console.log(0 && 'Jonas'); // 0
50 | //The last truthy value is returned
51 | console.log(7 && 'Jonas'); // Jonas
52 |
53 | console.log('Hello' && 23 && null && 'Jonas'); // null
54 |
55 | // Practical example
56 | if (restaurant.orderPizza) {
57 | restaurant.orderPizza('mushrooms', 'spinach');
58 | }
59 | //Block before gave same result as this line
60 | restaurant.orderPizza && restaurant.orderPizza('mushrooms', 'spinach');
61 |
--------------------------------------------------------------------------------
/09-Data-Structures-Operators/rest_pattern_parameters.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const restaurant = {
4 | name: 'Classico Italiano',
5 | location: 'Via Angelo Tavanti 23, Firenze, Italy',
6 | categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
7 | starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
8 | mainMenu: ['Pizza', 'Pasta', 'Risotto'],
9 |
10 | order(starterIndex, mainIndex) {
11 | return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
12 | },
13 |
14 | orderDelivery({ starterIndex = 1, mainIndex = 0, time = '20:00', address }) {
15 | console.log(
16 | `Order received! ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]} will be delivered to ${address} at ${time}`
17 | );
18 | },
19 |
20 | orderPasta(ing1, ing2, ing3) {
21 | console.log(
22 | `Here is your declicious pasta with ${ing1}, ${ing2} and ${ing3}`
23 | );
24 | },
25 |
26 | openingHours: {
27 | thu: {
28 | open: 12,
29 | close: 22,
30 | },
31 | fri: {
32 | open: 11,
33 | close: 23,
34 | },
35 | sat: {
36 | open: 0, // Open 24 hours
37 | close: 24,
38 | },
39 | },
40 |
41 | orderPizza: function (mainIngredient, ...otherIngredients) {
42 | console.log(mainIngredient);
43 | console.log(otherIngredients);
44 | },
45 | };
46 |
47 | //Spread, because on RIGHT side of =
48 | const arr = [1, 2, ...[3, 4]];
49 | console.log(arr);
50 |
51 | //REST, because on LEFT side of =
52 | const [a, b, ...others] = [1, 2, 3, 4, 5];
53 |
54 | console.log(a, b, others);
55 | //One REST in any destructring object and after that we could not assign a new variable
56 | const [pizza, , risotto, ...otherFood] = [
57 | ...restaurant.mainMenu,
58 | ...restaurant.starterMenu,
59 | ];
60 | console.log(pizza, risotto, otherFood);
61 |
62 | //Objects
63 | const { sat, ...weekdays } = restaurant.openingHours;
64 | console.log(weekdays);
65 |
66 | //Functions
67 |
68 | const add = function (...numbers) {
69 | console.log(numbers);
70 | let sum = 0;
71 | for (let i = 0; i < numbers.length; i++) sum += numbers[i];
72 | console.log(sum);
73 | };
74 | add(2, 3);
75 | add(5, 3, 7, 2);
76 | add(8, 2, 5, 3, 2, 1, 4);
77 |
78 | const x = [23, 5, 7];
79 | add(...x);
80 |
81 | restaurant.orderPizza('mushrooms', 'onions', 'olives', 'spinach');
82 |
--------------------------------------------------------------------------------
/07-Dom-Events-Fundamentals/style.css:
--------------------------------------------------------------------------------
1 | @import url('https://fonts.googleapis.com/css?family=Press+Start+2P&display=swap');
2 |
3 | * {
4 | margin: 0;
5 | padding: 0;
6 | box-sizing: inherit;
7 | }
8 |
9 | html {
10 | font-size: 62.5%;
11 | box-sizing: border-box;
12 | }
13 |
14 | body {
15 | font-family: 'Press Start 2P', sans-serif;
16 | color: #eee;
17 | background-color: #222;
18 | /* background-color: #60b347; */
19 | }
20 |
21 | /* LAYOUT */
22 | header {
23 | position: relative;
24 | height: 35vh;
25 | border-bottom: 7px solid #eee;
26 | }
27 |
28 | main {
29 | height: 65vh;
30 | color: #eee;
31 | display: flex;
32 | align-items: center;
33 | justify-content: space-around;
34 | }
35 |
36 | .left {
37 | width: 52rem;
38 | display: flex;
39 | flex-direction: column;
40 | align-items: center;
41 | }
42 |
43 | .right {
44 | width: 52rem;
45 | font-size: 2rem;
46 | }
47 |
48 | /* ELEMENTS STYLE */
49 | h1 {
50 | font-size: 4rem;
51 | text-align: center;
52 | position: absolute;
53 | width: 100%;
54 | top: 52%;
55 | left: 50%;
56 | transform: translate(-50%, -50%);
57 | }
58 |
59 | .number {
60 | background: #eee;
61 | color: #333;
62 | font-size: 6rem;
63 | width: 15rem;
64 | padding: 3rem 0rem;
65 | text-align: center;
66 | position: absolute;
67 | bottom: 0;
68 | left: 50%;
69 | transform: translate(-50%, 50%);
70 | }
71 |
72 | .between {
73 | font-size: 1.4rem;
74 | position: absolute;
75 | top: 2rem;
76 | right: 2rem;
77 | }
78 |
79 | .again {
80 | position: absolute;
81 | top: 2rem;
82 | left: 2rem;
83 | }
84 |
85 | .guess {
86 | background: none;
87 | border: 4px solid #eee;
88 | font-family: inherit;
89 | color: inherit;
90 | font-size: 5rem;
91 | padding: 2.5rem;
92 | width: 25rem;
93 | text-align: center;
94 | display: block;
95 | margin-bottom: 3rem;
96 | }
97 |
98 | .btn {
99 | border: none;
100 | background-color: #eee;
101 | color: #222;
102 | font-size: 2rem;
103 | font-family: inherit;
104 | padding: 2rem 3rem;
105 | cursor: pointer;
106 | }
107 |
108 | .btn:hover {
109 | background-color: #ccc;
110 | }
111 |
112 | .message {
113 | margin-bottom: 8rem;
114 | height: 3rem;
115 | }
116 |
117 | .label-score {
118 | margin-bottom: 2rem;
119 | }
120 |
--------------------------------------------------------------------------------
/09-Data-Structures-Operators/spread_operator.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const restaurant = {
4 | name: 'Classico Italiano',
5 | location: 'Via Angelo Tavanti 23, Firenze, Italy',
6 | categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
7 | starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
8 | mainMenu: ['Pizza', 'Pasta', 'Risotto'],
9 |
10 | order(starterIndex, mainIndex) {
11 | return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
12 | },
13 |
14 | orderDelivery({ starterIndex = 1, mainIndex = 0, time = '20:00', address }) {
15 | console.log(
16 | `Order received! ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]} will be delivered to ${address} at ${time}`
17 | );
18 | },
19 |
20 | orderPasta(ing1, ing2, ing3) {
21 | console.log(
22 | `Here is your declicious pasta with ${ing1}, ${ing2} and ${ing3}`
23 | );
24 | },
25 |
26 | orderPizza(mainIngredient, ...otherIngredients) {
27 | console.log(mainIngredient);
28 | console.log(otherIngredients);
29 | },
30 | };
31 |
32 | const arr = [7, 8, 9];
33 | const badNewArr = [1, 2, arr[0], arr[1], arr[2]];
34 | console.log(badNewArr);
35 |
36 | const newArr = [1, 2, ...arr];
37 | console.log(newArr);
38 |
39 | console.log(...newArr);
40 |
41 | const newMenu = [...restaurant.mainMenu, 'Gnocci'];
42 | console.log(newMenu);
43 | // Copy array
44 | const mainMenuCopy = [...restaurant.mainMenu];
45 | // Join 2 arrays
46 | const menu = [...restaurant.starterMenu, ...restaurant.mainMenu];
47 | console.log(menu);
48 | // Iterables: arrays, strings, maps, sets. NOT objects
49 | const str = 'Jonas';
50 | const letters = [...str, ' ', 'S.'];
51 | console.log(letters);
52 | console.log(...str);
53 | // console.log(`${...str} Schmedtmann`);
54 | // Real-world example
55 | const ingredients = [
56 | // prompt("Let's make pasta! Ingredient 1?"),
57 | // prompt('Ingredient 2?'),
58 | // prompt('Ingredient 3'),
59 | ];
60 | console.log(ingredients);
61 | restaurant.orderPasta(ingredients[0], ingredients[1], ingredients[2]);
62 | restaurant.orderPasta(...ingredients);
63 | // Objects
64 | const newRestaurant = { foundedIn: 1998, ...restaurant, founder: 'Guiseppe' };
65 | console.log(newRestaurant);
66 | const restaurantCopy = { ...restaurant };
67 | restaurantCopy.name = 'Ristorante Roma';
68 | console.log(restaurantCopy.name);
69 | console.log(restaurant.name);
70 |
--------------------------------------------------------------------------------
/07-Pig-Game/script.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | // Selecting elements
4 | const player0El = document.querySelector('.player--0');
5 | const player1El = document.querySelector('.player--1');
6 | const score0El = document.querySelector('#score--0');
7 | // getElementById is a bit faster than querySelector
8 | const score1El = document.getElementById('score--1');
9 | const current0El = document.getElementById('current--0');
10 | const current1El = document.getElementById('current--1');
11 | const diceEl = document.querySelector('.dice');
12 | const btnNew = document.querySelector('.btn--new');
13 | const btnRoll = document.querySelector('.btn--roll');
14 | const btnHold = document.querySelector('.btn--hold');
15 |
16 | //Starting conditions
17 | let scores, currentScore, activePlayer, playing;
18 | const init = function () {
19 | scores = [0, 0];
20 | currentScore = 0;
21 | activePlayer = 0;
22 | playing = true;
23 | diceEl.classList.add('hidden');
24 | score0El.textContent = 0;
25 | score1El.textContent = 0;
26 | score0El.textContent = 0;
27 | score1El.textContent = 0;
28 | current0El.textContent = 0;
29 | current1El.textContent = 0;
30 | player0El.classList.remove('player--winner');
31 | player1El.classList.remove('player--winner');
32 | player0El.classList.add('player--active');
33 | player1El.classList.remove('player--active');
34 | };
35 |
36 | init();
37 |
38 | const switchPlayer = function () {
39 | document.getElementById(`current--${activePlayer}`).textContent = 0;
40 | currentScore = 0;
41 | activePlayer = activePlayer === 0 ? 1 : 0;
42 | player0El.classList.toggle('player--active');
43 | player1El.classList.toggle('player--active');
44 | };
45 |
46 | //Rolling the dice functionality
47 | btnRoll.addEventListener('click', function () {
48 | if (playing) {
49 | // 1. Generating a random dice roll
50 | const dice = Math.trunc(Math.random() * 6) + 1;
51 |
52 | // 2.Display Dice
53 | diceEl.classList.remove('hidden');
54 | diceEl.src = `dice-${dice}.png`;
55 |
56 | // 3. Check for the rolled 1
57 | if (dice !== 1) {
58 | //Add dice to the current score
59 | currentScore += dice;
60 | document.getElementById(`current--${activePlayer}`).textContent =
61 | currentScore;
62 | } else {
63 | //Switch to next player
64 | switchPlayer();
65 | }
66 | }
67 | });
68 |
69 | btnHold.addEventListener('click', function () {
70 | if (playing) {
71 | // 1. Add current score to active player's score
72 | scores[activePlayer] += currentScore;
73 | //scores[1] = score[1] + currentScore
74 | document.getElementById(`score--${activePlayer}`).textContent =
75 | scores[activePlayer];
76 | // 2. Check if player's score is >= 100
77 |
78 | if (scores[activePlayer] >= 20) {
79 | // Finish the game
80 | playing = false;
81 | document
82 | .querySelector(`.player--${activePlayer}`)
83 | .classList.add('player--winner');
84 | document
85 | .querySelector(`.player--${activePlayer}`)
86 | .classList.remove('player--active');
87 | } else {
88 | //Switch to the next player
89 | switchPlayer();
90 | }
91 | }
92 | });
93 |
94 | btnNew.addEventListener('click', init);
95 |
--------------------------------------------------------------------------------
/07-Pig-Game/style.css:
--------------------------------------------------------------------------------
1 | @import url('https://fonts.googleapis.com/css2?family=Nunito&display=swap');
2 |
3 | * {
4 | margin: 0;
5 | padding: 0;
6 | box-sizing: inherit;
7 | }
8 |
9 | html {
10 | font-size: 62.5%;
11 | box-sizing: border-box;
12 | }
13 |
14 | body {
15 | font-family: 'Nunito', sans-serif;
16 | font-weight: 400;
17 | height: 100vh;
18 | color: #333;
19 | background-image: linear-gradient(to top left, #753682 0%, #bf2e34 100%);
20 | display: flex;
21 | align-items: center;
22 | justify-content: center;
23 | }
24 |
25 | /* LAYOUT */
26 | main {
27 | position: relative;
28 | width: 100rem;
29 | height: 60rem;
30 | background-color: rgba(255, 255, 255, 0.35);
31 | backdrop-filter: blur(200px);
32 | filter: blur();
33 | box-shadow: 0 3rem 5rem rgba(0, 0, 0, 0.25);
34 | border-radius: 9px;
35 | overflow: hidden;
36 | display: flex;
37 | }
38 |
39 | .player {
40 | flex: 50%;
41 | padding: 9rem;
42 | display: flex;
43 | flex-direction: column;
44 | align-items: center;
45 | transition: all 0.75s;
46 | }
47 |
48 | /* ELEMENTS */
49 | .name {
50 | position: relative;
51 | font-size: 4rem;
52 | text-transform: uppercase;
53 | letter-spacing: 1px;
54 | word-spacing: 2px;
55 | font-weight: 300;
56 | margin-bottom: 1rem;
57 | }
58 |
59 | .score {
60 | font-size: 8rem;
61 | font-weight: 300;
62 | color: #c7365f;
63 | margin-bottom: auto;
64 | }
65 |
66 | .player--active {
67 | background-color: rgba(255, 255, 255, 0.4);
68 | }
69 | .player--active .name {
70 | font-weight: 700;
71 | }
72 | .player--active .score {
73 | font-weight: 400;
74 | }
75 |
76 | .player--active .current {
77 | opacity: 1;
78 | }
79 |
80 | .current {
81 | background-color: #c7365f;
82 | opacity: 0.8;
83 | border-radius: 9px;
84 | color: #fff;
85 | width: 65%;
86 | padding: 2rem;
87 | text-align: center;
88 | transition: all 0.75s;
89 | }
90 |
91 | .current-label {
92 | text-transform: uppercase;
93 | margin-bottom: 1rem;
94 | font-size: 1.7rem;
95 | color: #ddd;
96 | }
97 |
98 | .current-score {
99 | font-size: 3.5rem;
100 | }
101 |
102 | /* ABSOLUTE POSITIONED ELEMENTS */
103 | .btn {
104 | position: absolute;
105 | left: 50%;
106 | transform: translateX(-50%);
107 | color: #444;
108 | background: none;
109 | border: none;
110 | font-family: inherit;
111 | font-size: 1.8rem;
112 | text-transform: uppercase;
113 | cursor: pointer;
114 | font-weight: 400;
115 | transition: all 0.2s;
116 |
117 | background-color: white;
118 | background-color: rgba(255, 255, 255, 0.6);
119 | backdrop-filter: blur(10px);
120 |
121 | padding: 0.7rem 2.5rem;
122 | border-radius: 50rem;
123 | box-shadow: 0 1.75rem 3.5rem rgba(0, 0, 0, 0.1);
124 | }
125 |
126 | .btn::first-letter {
127 | font-size: 2.4rem;
128 | display: inline-block;
129 | margin-right: 0.7rem;
130 | }
131 |
132 | .btn--new {
133 | top: 4rem;
134 | }
135 | .btn--roll {
136 | top: 39.3rem;
137 | }
138 | .btn--hold {
139 | top: 46.1rem;
140 | }
141 |
142 | .btn:active {
143 | transform: translate(-50%, 3px);
144 | box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.15);
145 | }
146 |
147 | .btn:focus {
148 | outline: none;
149 | }
150 |
151 | .dice {
152 | position: absolute;
153 | left: 50%;
154 | top: 16.5rem;
155 | transform: translateX(-50%);
156 | height: 10rem;
157 | box-shadow: 0 2rem 5rem rgba(0, 0, 0, 0.2);
158 | }
159 |
160 | .player--winner {
161 | background-color: #2f2f2f;
162 | }
163 |
164 | .player--winner .name {
165 | font-weight: 700;
166 | color: #c7365f;
167 | }
168 |
169 | .hidden {
170 | display: none;
171 | }
--------------------------------------------------------------------------------
/07-Dom-Events-Fundamentals/script.js:
--------------------------------------------------------------------------------
1 | /*
2 | What is DOM?
3 | DOCUMENT OBJECT MODEL: Structured representation of HTML documents. Allows Javascript to access HTML elements and Styles to Manipulate them.
4 | DOM and properties for DOM MANIPULATION not part of JS (ECMA) for example document.querySelector()
5 | WEB APIs DOM Methods and Properties (Timers, Fetch) can interact with JS
6 | */
7 | 'use strict';
8 | /*
9 | console.log(document.querySelector('.message').textContent);
10 |
11 | document.querySelector('.message').textContent = '🎉 Correct Number!';
12 |
13 | document.querySelector('.number').textContent = 13;
14 | document.querySelector('.score').textContent = 20;
15 |
16 | console.log(document.querySelector('.guess').value);
17 | document.querySelector('.guess').value = 23;
18 |
19 | const x = function () {
20 | console.log(23);
21 | };
22 | */
23 | let secretNumber = Math.trunc(Math.random() * 20) + 1;
24 | let score = 20;
25 | let highscore = 0;
26 |
27 | const displayMessage = function (message) {
28 | document.querySelector('.message').textContent = message;
29 | };
30 | document.querySelector('.check').addEventListener('click', function () {
31 | const guess = Number(document.querySelector('.guess').value);
32 | console.log(guess, typeof guess);
33 |
34 | // When there is no input
35 | if (!guess) {
36 | displayMessage('⛔️ No number!');
37 | // When player wins
38 | } else if (guess === secretNumber) {
39 | displayMessage('🎉 Correct Number!');
40 |
41 | document.querySelector('.number').textContent = secretNumber;
42 | document.querySelector('body').style.backgroundColor = '#60b347';
43 | document.querySelector('.number').style.width = '30rem';
44 |
45 | if (score > highscore) {
46 | highscore = score;
47 | document.querySelector('.highscore').textContent = highscore;
48 | }
49 |
50 | // When guess is wrong
51 | } else if (guess !== secretNumber) {
52 | if (score > 1) {
53 | displayMessage(guess > secretNumber ? '📈 Too high!' : '📉 Too low!');
54 | score--;
55 | document.querySelector('.score').textContent = score;
56 | } else {
57 | document.querySelector('.message').textContent = ' 💥 You lost the game!';
58 | document.querySelector('.score').textContent = 0;
59 | }
60 | }
61 | // When guess is too high
62 |
63 | // } else if (guess > secretNumber) {
64 | // if (score > 1) {
65 | // document.querySelector('.message').textContent = '📈 Too high!';
66 | // score--;
67 | // document.querySelector('.score').textContent = score;
68 | // } else {
69 | // document.querySelector('.message').textContent = ' 💥 You lost the game!';
70 | // document.querySelector('.score').textContent = 0;
71 | // }
72 | // // When gues is too low
73 | // } else if (guess < secretNumber) {
74 | // if (score > 1) {
75 | // document.querySelector('.message').textContent = '📉 Too low!';
76 | // score--;
77 | // document.querySelector('.score').textContent = score;
78 | // } else {
79 | // document.querySelector('.message').textContent = ' 💥 You lost the game!';
80 | // document.querySelector('.score').textContent = 0;
81 | // }
82 | // }
83 | });
84 |
85 | /*
86 | Coding Challenge #1
87 | Implement a game rest functionality, so that the player can make a new guess!
88 | Your tasks:
89 | 1. Select the element with the 'again' class and attach a click event handler
90 | 2. In the handler function, restore initial values of the 'score' and
91 | 'secretNumber' variables
92 | 3. Restore the initial conditions of the message, number, score and guess input
93 | fields
94 | 4. Also restore the original background color (#222) and number width (15rem)
95 | GOOD LUCK 😀
96 | */
97 | document.querySelector('.again').addEventListener('click', function () {
98 | score = 20;
99 | document.querySelector('.score').textContent = score;
100 | secretNumber = Math.trunc(Math.random() * 20) + 1;
101 | document.querySelector('.number').textContent = '?';
102 | displayMessage('Start guessing...');
103 | document.querySelector('.guess').value = '';
104 | document.querySelector('body').style.backgroundColor = '#222';
105 | document.querySelector('.number').style.width = '15rem';
106 | });
107 |
--------------------------------------------------------------------------------