Professional Documents
Culture Documents
/*
////////////////////////////////////
// Linking a JavaScript File
let js = "amazing";
console.log(40 + 8 + 23 - 10);
////////////////////////////////////
// Values and Variables
console.log("Jonas");
console.log(23);
let firstName = "Matilda";
console.log(firstName);
console.log(firstName);
console.log(firstName);
// Variable name conventions
let jonas_matilda = "JM";
let $function = 27;
let person = "jonas";
let PI = 3.1415;
let myFirstJob = "Coder";
let myCurrentJob = "Teacher";
let job1 = "programmer";
let job2 = "teacher";
1
console.log(myFirstJob);
////////////////////////////////////
// Data Types
let javascriptIsFun = true;
console.log(javascriptIsFun);
// console.log(typeof true);
console.log(typeof javascriptIsFun);
// console.log(typeof 23);
// console.log(typeof 'Jonas');
javascriptIsFun = 'YES!';
console.log(typeof javascriptIsFun);
let year;
console.log(year);
console.log(typeof year);
year = 1991;
console.log(typeof year);
console.log(typeof null);
////////////////////////////////////
// let, const and var
let age = 30;
age = 31;
const birthYear = 1991;
// birthYear = 1990;
// const job;
2
var job = 'programmer';
job = 'teacher'
lastName = 'Schmedtmann';
console.log(lastName);
////////////////////////////////////
// Basic Operators
// Math operators
const now = 2037;
const ageJonas = now - 1991;
const ageSarah = now - 2018;
console.log(ageJonas, ageSarah);
console.log(ageJonas * 2, ageJonas / 10, 2 ** 3);
// 2 ** 3 means 2 to the power of 3 = 2 * 2 * 2
const firstName = 'Jonas';
const lastName = 'Schmedtmann';
console.log(firstName + ' ' + lastName);
// Assignment operators
let x = 10 + 5; // 15
x += 10; // x = x + 10 = 25
x *= 4; // x = x * 4 = 100
x++; // x = x + 1
x--;
x--;
console.log(x);
// Comparison operators
3
console.log(ageJonas > ageSarah); // >, <, >=, <=
console.log(ageSarah >= 18);
const isFullAge = ageSarah >= 18;
console.log(now - 1991 > now - 2018);
////////////////////////////////////
// Operator Precedence
const now = 2037;
const ageJonas = now - 1991;
const ageSarah = now - 2018;
console.log(now - 1991 > now - 2018);
let x, y;
x = y = 25 - 10 - 5; // x = y = 10, x = 10
console.log(x, y);
const averageAge = (ageJonas + ageSarah) / 2;
console.log(ageJonas, ageSarah, averageAge);
*/
////////////////////////////////////
// Coding Challenge #1
/*
Mark and John are trying to compare their BMI (Body Mass Index), which is calculated using the formula: BMI = mass
/ height ** 2 = mass / (height * height). (mass in kg and height in meter).
1. Store Mark's and John's mass and height in variables
2. Calculate both their BMIs using the formula (you can even implement both versions)
4
3. Create a boolean variable 'markHigherBMI' containing information about whether Mark has a higher BMI than John
TEST DATA 1: Marks weights 78 kg and is 1.69 m tall. John weights 92 kg and is 1.95 m tall.
TEST DATA 2: Marks weights 95 kg and is 1.88 m tall. John weights 85 kg and is 1.76 m tall.
GOOD LUCK 😀
*/
// const massMark = 78;
// const heightMark = 1.69;
// const massJohn = 92;
// const heightJohn = 1.95;
/*
const massMark = 95;
const heightMark = 1.88;
const massJohn = 85;
const heightJohn = 1.76;
const BMIMark = massMark / heightMark ** 2;
const BMIJohn = massJohn / (heightJohn * heightJohn);
const markHigherBMI = BMIMark > BMIJohn;
console.log(BMIMark, BMIJohn, markHigherBMI);
////////////////////////////////////
// Strings and Template Literals
const firstName = 'Jonas';
const job = 'teacher';
const birthYear = 1991;
const year = 2037;
5
const jonas = "I'm " + firstName + ', a ' + (year - birthYear) + ' year old ' + job + '!';
console.log(jonas);
const jonasNew = `I'm ${firstName}, a ${year - birthYear} year old ${job}!`;
console.log(jonasNew);
console.log(`Just a regular string...`);
console.log('String with \n\
multiple \n\
lines');
console.log(`String
multiple
lines`);
////////////////////////////////////
// Taking Decisions: if / else Statements
const age = 15;
if (age >= 18) {
console.log('Sarah can start driving license 🚗');
} else {
const yearsLeft = 18 - age;
console.log(`Sarah is too young. Wait another ${yearsLeft} years :)`);
const birthYear = 2012;
let century;
6
if (birthYear <= 2000) {
century = 20;
} else {
century = 21;
console.log(century);
*/
////////////////////////////////////
// Coding Challenge #2
/*
Use the BMI example from Challenge #1, and the code you already wrote, and improve it:
1. Print a nice output to the console, saying who has the higher BMI. The message can be either "Mark's BMI is highe
r than John's!" or "John's BMI is higher than Mark's!"
2. Use a template literal to include the BMI values in the outputs. Example: "Mark's BMI (28.3) is higher than John's (
23.9)!"
HINT: Use an if/else statement 😉
GOOD LUCK 😀
*/
/*
const massMark = 78;
const heightMark = 1.69;
const massJohn = 92;
const heightJohn = 1.95;
// const massMark = 95;
// const heightMark = 1.88;
7
// const massJohn = 85;
// const heightJohn = 1.76;
const BMIMark = massMark / heightMark ** 2;
const BMIJohn = massJohn / (heightJohn * heightJohn);
console.log(BMIMark, BMIJohn);
if (BMIMark > BMIJohn) {
console.log(`Mark's BMI (${BMIMark}) is higher than John's (${BMIJohn})!`)
} else {
console.log(`John's BMI (${BMIJohn}) is higher than Marks's (${BMIMark})!`)
////////////////////////////////////
// Type Conversion and Coercion
// type conversion
const inputYear = '1991';
console.log(Number(inputYear), inputYear);
console.log(Number(inputYear) + 18);
console.log(Number('Jonas'));
console.log(typeof NaN);
console.log(String(23), 23);
// type coercion
console.log('I am ' + 23 + ' years old');
console.log('23' - '10' - 3);
console.log('23' / '2');
console.log('23' > '18');
8
let n = '1' + 1; // '11'
n = n - 1;
console.log(n);
////////////////////////////////////
// Truthy and Falsy Values
// 5 falsy values: 0, '', undefined, null, NaN
console.log(Boolean(0));
console.log(Boolean(undefined));
console.log(Boolean('Jonas'));
console.log(Boolean({}));
console.log(Boolean(''));
const money = 100;
if (money) {
console.log("Don't spend it all ;)");
} else {
console.log('You should get a job!');
let height = 0;
if (height) {
console.log('YAY! Height is defined');
} else {
console.log('Height is UNDEFINED');
////////////////////////////////////
// Equality Operators: == vs. ===
const age = '18';
if (age === 18) console.log('You just became an adult :D (strict)');
9
if (age == 18) console.log('You just became an adult :D (loose)');
const favourite = Number(prompt("What's your favourite number?"));
console.log(favourite);
console.log(typeof favourite);
if (favourite === 23) { // 22 === 23 -> FALSE
console.log('Cool! 23 is an amzaing number!')
} else if (favourite === 7) {
console.log('7 is also a cool number')
} else if (favourite === 9) {
console.log('9 is also a cool number')
} else {
console.log('Number is not 23 or 7 or 9')
if (favourite !== 23) console.log('Why not 23?');
////////////////////////////////////
// Logical Operators
const hasDriversLicense = true; // A
const hasGoodVision = true; // B
console.log(hasDriversLicense && hasGoodVision);
console.log(hasDriversLicense || hasGoodVision);
console.log(!hasDriversLicense);
// if (hasDriversLicense && hasGoodVision) {
// console.log('Sarah is able to drive!');
// } else {
// console.log('Someone else should drive...');
10
// }
const isTired = false; // C
console.log(hasDriversLicense && hasGoodVision && isTired);
if (hasDriversLicense && hasGoodVision && !isTired) {
console.log('Sarah is able to drive!');
} else {
console.log('Someone else should drive...');
*/
////////////////////////////////////
// Coding Challenge #3
/*
There are two gymnastics teams, Dolphins and Koalas. They compete against each other 3 times. The winner with th
e highest average score wins the a trophy!
1. Calculate the average score for each team, using the test data below
2. Compare the team's average scores to determine the winner of the competition, and print it to the console. Don't fo
rget that there can be a draw, so test for that as well (draw means they have the same average score).
3. BONUS 1: Include a requirement for a minimum score of 100. With this rule, a team only wins if it has a higher scor
e than the other team, and the same time a score of at least 100 points. HINT: Use a logical operator to test for minim
um score, as well as multiple else-if blocks 😉
4. BONUS 2: Minimum score also applies to a draw! So a draw only happens when both teams have the same score
and both have a score greater or equal 100 points. Otherwise, no team wins the trophy.
TEST DATA: Dolphins score 96, 108 and 89. Koalas score 88, 91 and 110
TEST DATA BONUS 1: Dolphins score 97, 112 and 101. Koalas score 109, 95 and 123
TEST DATA BONUS 2: Dolphins score 97, 112 and 101. Koalas score 109, 95 and 106
11
GOOD LUCK 😀
*/
/*
// const scoreDolphins = (96 + 108 + 89) / 3;
// const scoreKoalas = (88 + 91 + 110) / 3;
// console.log(scoreDolphins, scoreKoalas);
// if (scoreDolphins > scoreKoalas) {
// console.log('Dolphins win the trophy 🏆');
// } else if (scoreKoalas > scoreDolphins) {
// console.log('Koalas win the trophy 🏆');
// } else if (scoreDolphins === scoreKoalas) {
// console.log('Both win the trophy!');
// }
// BONUS 1
const scoreDolphins = (97 + 112 + 80) / 3;
const scoreKoalas = (109 + 95 + 50) / 3;
console.log(scoreDolphins, scoreKoalas);
if (scoreDolphins > scoreKoalas && scoreDolphins >= 100) {
console.log('Dolphins win the trophy 🏆');
} else if (scoreKoalas > scoreDolphins && scoreKoalas >= 100) {
console.log('Koalas win the trophy 🏆');
} else if (scoreDolphins === scoreKoalas && scoreDolphins >= 100 && scoreKoalas >= 100) {
console.log('Both win the trophy!');
} else {
console.log('No one wins the trophy 😭');
12
////////////////////////////////////
// The switch Statement
const day = 'friday';
switch (day) {
case 'monday': // day === 'monday'
console.log('Plan course structure');
console.log('Go to coding meetup');
break;
case 'tuesday':
console.log('Prepare theory videos');
break;
case 'wednesday':
case 'thursday':
console.log('Write code examples');
break;
case 'friday':
console.log('Record videos');
break;
case 'saturday':
case 'sunday':
console.log('Enjoy the weekend :D');
break;
default:
console.log('Not a valid day!');
if (day === 'monday') {
console.log('Plan course structure');
console.log('Go to coding meetup');
} else if (day === 'tuesday') {
console.log('Prepare theory videos');
13
} else if (day === 'wednesday' || day === 'thursday') {
console.log('Write code examples');
} else if (day === 'friday') {
console.log('Record videos');
} else if (day === 'saturday' || day === 'sunday') {
console.log('Enjoy the weekend :D');
} else {
console.log('Not a valid day!');
////////////////////////////////////
// Statements and Expressions
3 + 4
1991
true && false && !false
if (23 > 10) {
const str = '23 is bigger';
const me = 'Jonas';
console.log(`I'm ${2037 - 1991} years old ${me}`);
////////////////////////////////////
// The Conditional (Ternary) Operator
const age = 23;
// age >= 18 ? console.log('I like to drink wine 🍷') : console.log('I like to drink water 💧');
const drink = age >= 18 ? 'wine 🍷' : 'water 💧';
console.log(drink);
let drink2;
if (age >= 18) {
drink2 = 'wine 🍷';
14
} else {
drink2 = 'water 💧';
console.log(drink2);
console.log(`I like to drink ${age >= 18 ? 'wine 🍷' : 'water 💧'}`);
*/
////////////////////////////////////
// Coding Challenge #4
/*
Steven wants to build a very simple tip calculator for whenever he goes eating in a resturant. In his country, it's usual
to tip 15% if the bill value is between 50 and 300. If the value is different, the tip is 20%.
1. Your task is to caluclate the tip, depending on the bill value. Create a variable called 'tip' for this. It's not allowed to
use an if/else statement 😅 (If it's easier for you, you can start with an if/else statement, and then try to convert it to a t
ernary operator!)
2. Print a string to the console containing the bill value, the tip, and the final value (bill + tip). Example: 'The bill was 2
75, the tip was 41.25, and the total value 316.25'
TEST DATA: Test for bill values 275, 40 and 430
HINT: To calculate 20% of a value, simply multiply it by 20/100 = 0.2
HINT: Value X is between 50 and 300, if it's >= 50 && <= 300 😉
GOOD LUCK 😀
*/
/*
const bill = 430;
const tip = bill <= 300 && bill >= 50 ? bill * 0.15 : bill * 0.2;
console.log(`The bill was ${bill}, the tip was ${tip}, and the total value ${bill + tip}`);
*/
15
Fundamental 2
'use strict';
/*
///////////////////////////////////////
// Activating Strict Mode
let hasDriversLicense = false;
const passTest = true;
if (passTest) hasDriversLicense = true;
if (hasDriversLicense) console.log('I can drive :D');
// const interface = 'Audio';
// const private = 534;
///////////////////////////////////////
// Functions
function logger() {
console.log('My name is Jonas');
// calling / running / invoking function
logger();
logger();
logger();
function fruitProcessor(apples, oranges) {
const juice = `Juice with ${apples} apples and ${oranges} oranges.`;
return juice;
const appleJuice = fruitProcessor(5, 0);
console.log(appleJuice);
const appleOrangeJuice = fruitProcessor(2, 4);
console.log(appleOrangeJuice);
const num = Number('23');
16
///////////////////////////////////////
// Function Declarations vs. Expressions
// Function declaration
function calcAge1(birthYeah) {
return 2037 - birthYeah;
const age1 = calcAge1(1991);
// Function expression
const calcAge2 = function (birthYeah) {
return 2037 - birthYeah;
const age2 = calcAge2(1991);
console.log(age1, age2);
///////////////////////////////////////
// Arrow functions
const calcAge3 = birthYeah => 2037 - birthYeah;
const age3 = calcAge3(1991);
console.log(age3);
const yearsUntilRetirement = (birthYeah, firstName) => {
const age = 2037 - birthYeah;
const retirement = 65 - age;
// return retirement;
return `${firstName} retires in ${retirement} years`;
console.log(yearsUntilRetirement(1991, 'Jonas')); console.log(yearsUntilRetirement(1980, 'Bob'));
17
///////////////////////////////////////
// Functions Calling Other Functions
function cutFruitPieces(fruit) {
return fruit * 4;
function fruitProcessor(apples, oranges) {
const applePieces = cutFruitPieces(apples);
const orangePieces = cutFruitPieces(oranges);
const juice = `Juice with ${applePieces} piece of apple and ${orangePieces} pieces of orange.`;
return juice;
console.log(fruitProcessor(2, 3));
///////////////////////////////////////
// Reviewing Functions
const calcAge = function (birthYeah) {
return 2037 - birthYeah;
const yearsUntilRetirement = function (birthYeah, firstName) {
const age = calcAge(birthYeah);
const retirement = 65 - age;
if (retirement > 0) {
console.log(`${firstName} retires in ${retirement} years`);
return retirement;
} else {
console.log(`${firstName} has already retired 🎉`);
return -1;
}
18
console.log(yearsUntilRetirement(1991, 'Jonas'));
console.log(yearsUntilRetirement(1950, 'Mike'));
*/
///////////////////////////////////////
// Coding Challenge #1
/*
Back to the two gymnastics teams, the Dolphins and the Koalas! There is a new gymnastics discipline, which works d
ifferently.
Each team competes 3 times, and then the average of the 3 scores is calculated (so one average score per team).
A team ONLY wins if it has at least DOUBLE the average score of the other team. Otherwise, no team wins!
1. Create an arrow function 'calcAverage' to calculate the average of 3 scores
2. Use the function to calculate the average for both teams
3. Create a function 'checkWinner' that takes the average score of each team as parameters ('avgDolhins' and 'avgKo
alas'), and then logs the winner to the console, together with the victory points, according to the rule above. Example:
"Koalas win (30 vs. 13)".
4. Use the 'checkWinner' function to determine the winner for both DATA 1 and DATA 2.
5. Ignore draws this time.
TEST DATA 1: Dolphins score 44, 23 and 71. Koalas score 65, 54 and 49
TEST DATA 2: Dolphins score 85, 54 and 41. Koalas score 23, 34 and 27
HINT: To calculate average of 3 values, add them all together and divide by 3
HINT: To check if number A is at least double number B, check for A >= 2 * B. Apply this to the team's average score
s 😉
GOOD LUCK 😀
*/
/*
const calcAverage = (a, b, c) => (a + b + c) / 3;
19
console.log(calcAverage(3, 4, 5));
// Test 1
let scoreDolphins = calcAverage(44, 23, 71);
let scoreKoalas = calcAverage(65, 54, 49);
console.log(scoreDolphins, scoreKoalas);
const checkWinner = function (avgDolphins, avgKoalas) {
if (avgDolphins >= 2 * avgKoalas) {
console.log(`Dolphins win 🏆 (${avgDolphins} vs. ${avgKoalas})`);
} else if (avgKoalas >= 2 * avgDolphins) {
console.log(`Koalas win 🏆 (${avgKoalas} vs. ${avgDolphins})`);
} else {
console.log('No team wins...');
}
checkWinner(scoreDolphins, scoreKoalas);
checkWinner(576, 111);
// Test 2
scoreDolphins = calcAverage(85, 54, 41);
scoreKoalas = calcAverage(23, 34, 27);
console.log(scoreDolphins, scoreKoalas);
checkWinner(scoreDolphins, scoreKoalas);
///////////////////////////////////////
// Introduction to Arrays
const friend1 = 'Michael';
const friend2 = 'Steven';
const friend3 = 'Peter';
const friends = ['Michael', 'Steven', 'Peter'];
20
console.log(friends);
const y = new Array(1991, 1984, 2008, 2020);
console.log(friends[0]);
console.log(friends[2]);
console.log(friends.length);
console.log(friends[friends.length - 1]);
friends[2] = 'Jay';
console.log(friends);
// friends = ['Bob', 'Alice']
const firstName = 'Jonas';
const jonas = [firstName, 'Schmedtmann', 2037 - 1991, 'teacher', friends];
console.log(jonas);
console.log(jonas.length);
// Exercise
const calcAge = function (birthYeah) {
return 2037 - birthYeah;
const years = [1990, 1967, 2002, 2010, 2018];
const age1 = calcAge(years[0]);
const age2 = calcAge(years[1]);
const age3 = calcAge(years[years.length - 1]);
console.log(age1, age2, age3);
const ages = [calcAge(years[0]), calcAge(years[1]), calcAge(years[years.length - 1])];
console.log(ages);
21
///////////////////////////////////////
// Basic Array Operations (Methods)
const friends = ['Michael', 'Steven', 'Peter'];
// Add elements
const newLength = friends.push('Jay');
console.log(friends);
console.log(newLength);
friends.unshift('John');
console.log(friends);
// Remove elements
friends.pop(); // Last
const popped = friends.pop();
console.log(popped);
console.log(friends);
friends.shift(); // First
console.log(friends);
console.log(friends.indexOf('Steven'));
console.log(friends.indexOf('Bob'));
friends.push(23);
console.log(friends.includes('Steven'));
console.log(friends.includes('Bob'));
console.log(friends.includes(23));
if (friends.includes('Steven')) {
console.log('You have a friend called Steven');
22
*////////////////////////////////////////
// Coding Challenge #2
/*
Steven is still building his tip calculator, using the same rules as before: Tip 15% of the bill if the bill value is between
50 and 300, and if the value is different, the tip is 20%.
1. Write a function 'calcTip' that takes any bill value as an input and returns the corresponding tip, calculated based o
n the rules above (you can check out the code from first tip calculator challenge if you need to). Use the function type
you like the most. Test the function using a bill value of 100.
2. And now let's use arrays! So create an array 'bills' containing the test data below.
3. Create an array 'tips' containing the tip value for each bill, calculated from the function you created before.
4. BONUS: Create an array 'total' containing the total values, so the bill + tip.
TEST DATA: 125, 555 and 44
HINT: Remember that an array needs a value in each position, and that value can actually be the returned value of a
function! So you can just call a function as array values (so don't store the tip values in separate variables first, but rig
ht in the new array) 😉
GOOD LUCK 😀
*/
/*
const calcTip = function (bill) {
return bill >= 50 && bill <= 300 ? bill * 0.15 : bill * 0.2;
// const calcTip = bill => bill >= 50 && bill <= 300 ? bill * 0.15 : bill * 0.2;
const bills = [125, 555, 44];
const tips = [calcTip(bills[0]), calcTip(bills[1]), calcTip(bills[2])];
const totals = [bills[0] + tips[0], bills[1] + tips[1], bills[2] + tips[2]];
23
console.log(bills, tips, totals);
///////////////////////////////////////
// Introduction to Objects
const jonasArray = [
'Jonas',
'Schmedtmann',
2037 - 1991,
'teacher',
['Michael', 'Peter', 'Steven']
];
const jonas = {
firstName: 'Jonas',
lastName: 'Schmedtmann',
age: 2037 - 1991,
job: 'teacher',
friends: ['Michael', 'Peter', 'Steven']
};
///////////////////////////////////////
// Dot vs. Bracket Notation
const jonas = {
firstName: 'Jonas',
lastName: 'Schmedtmann',
age: 2037 - 1991,
job: 'teacher',
friends: ['Michael', 'Peter', 'Steven']
};
console.log(jonas);
console.log(jonas.lastName);
console.log(jonas['lastName']);
24
const nameKey = 'Name';
console.log(jonas['first' + nameKey]);
console.log(jonas['last' + nameKey]);
// console.log(jonas.'last' + nameKey)
const interestedIn = prompt('What do you want to know about Jonas? Choose between firstName, lastName, age, job
, and friends');
if (jonas[interestedIn]) {
console.log(jonas[interestedIn]);
} else {
console.log('Wrong request! Choose between firstName, lastName, age, job, and friends');
jonas.location = 'Portugal';
jonas['twitter'] = '@jonasschmedtman';
console.log(jonas);
// Challenge
// "Jonas has 3 friends, and his best friend is called Michael"
console.log(`${jonas.firstName} has ${jonas.friends.length} friends, and his best friend is called ${jonas.friends[0]}`);
///////////////////////////////////////
// Object Methods
const jonas = {
firstName: 'Jonas',
lastName: 'Schmedtmann',
birthYeah: 1991,
job: 'teacher',
25
friends: ['Michael', 'Peter', 'Steven'],
hasDriversLicense: true,
// calcAge: function (birthYeah) {
// return 2037 - birthYeah;
// }
// calcAge: function () {
// // console.log(this);
// return 2037 - this.birthYeah;
// }
calcAge: function () {
this.age = 2037 - this.birthYeah;
return this.age;
},
getSummary: function () {
return `${this.firstName} is a ${this.calcAge()}-year old ${jonas.job}, and he has ${this.hasDriversLicense ? 'a' : 'no'}
driver's license.`
}
};
console.log(jonas.calcAge());
console.log(jonas.age);
console.log(jonas.age);
console.log(jonas.age);
// Challenge
// "Jonas is a 46-year old teacher, and he has a driver's license"
console.log(jonas.getSummary());
*/
26
///////////////////////////////////////
// Coding Challenge #3
/*
Let's go back to Mark and John comparing their BMIs! This time, let's use objects to implement the calculations! Rem
ember: BMI = mass / height ** 2 = mass / (height * height). (mass in kg and height in meter)
1. For each of them, create an object with properties for their full name, mass, and height (Mark Miller and John Smit
h)
2. Create a 'calcBMI' method on each object to calculate the BMI (the same method on both objects). Store the BMI v
alue to a property, and also return it from the method.
3. Log to the console who has the higher BMI, together with the full name and the respective BMI. Example: "John S
mith's BMI (28.3) is higher than Mark Miller's (23.9)!"
TEST DATA: Marks weights 78 kg and is 1.69 m tall. John weights 92 kg and is 1.95 m tall.
GOOD LUCK 😀
*/
/*
const mark = {
fullName: 'Mark Miller',
mass: 78,
height: 1.69,
calcBMI: function () {
this.bmi = this.mass / this.height ** 2;
return this.bmi;
}
};
const john = {
fullName: 'John Smith',
27
mass: 92,
height: 1.95,
calcBMI: function () {
this.bmi = this.mass / this.height ** 2;
return this.bmi;
}
};
mark.calcBMI();
john.calcBMI();
console.log(mark.bmi, john.bmi);
// "John Smith's BMI (28.3) is higher than Mark Miller's (23.9)!"
if (mark.bmi > john.bmi) {
console.log(`${mark.fullName}'s BMI (${mark.bmi}) is higher than ${john.fullName}'s BMI (${john.bmi})`)
} else if (john.bmi > mark.bmi) {
console.log(`${john.fullName}'s BMI (${john.bmi}) is higher than ${mark.fullName}'s BMI (${mark.bmi})`)
///////////////////////////////////////
// Iteration: The for Loop
// console.log('Lifting weights repetition 1 🏋️♀️');
// console.log('Lifting weights repetition 2 🏋️♀️');
// console.log('Lifting weights repetition 3 🏋️♀️');
// console.log('Lifting weights repetition 4 🏋️♀️');
// console.log('Lifting weights repetition 5 🏋️♀️');
// console.log('Lifting weights repetition 6 🏋️♀️');
// console.log('Lifting weights repetition 7 🏋️♀️');
28
// console.log('Lifting weights repetition 8 🏋️♀️');
// console.log('Lifting weights repetition 9 🏋️♀️');
// console.log('Lifting weights repetition 10 🏋️♀️');
// for loop keeps running while condition is TRUE
for (let rep = 1; rep <= 30; rep++) {
console.log(`Lifting weights repetition ${rep} 🏋️♀
️`);
///////////////////////////////////////
// Looping Arrays, Breaking and Continuing
const jonas = [
'Jonas',
'Schmedtmann',
2037 - 1991,
'teacher',
['Michael', 'Peter', 'Steven'],
true
];
const types = [];
// console.log(jonas[0])
// console.log(jonas[1])
// ...
// console.log(jonas[4])
// jonas[5] does NOT exist
for (let i = 0; i < jonas.length; i++) {
// Reading from jonas array
console.log(jonas[i], typeof jonas[i]);
29
// Filling types array
// types[i] = typeof jonas[i];
types.push(typeof jonas[i]);
console.log(types);
const years = [1991, 2007, 1969, 2020];
const ages = [];
for (let i = 0; i < years.length; i++) {
ages.push(2037 - years[i]);
console.log(ages);
// continue and break
console.log('--- ONLY STRINGS ---')
for (let i = 0; i < jonas.length; i++) {
if (typeof jonas[i] !== 'string') continue;
console.log(jonas[i], typeof jonas[i]);
console.log('--- BREAK WITH NUMBER ---')
for (let i = 0; i < jonas.length; i++) {
if (typeof jonas[i] === 'number') break;
console.log(jonas[i], typeof jonas[i]);
///////////////////////////////////////
30
// Looping Backwards and Loops in Loops
const jonas = [
'Jonas',
'Schmedtmann',
2037 - 1991,
'teacher',
['Michael', 'Peter', 'Steven'],
true
];
// 0, 1, ..., 4
// 4, 3, ..., 0
for (let i = jonas.length - 1; i >= 0; i--) {
console.log(i, jonas[i]);
for (let exercise = 1; exercise < 4; exercise++) {
console.log(`-------- Starting exercise ${exercise}`);
for (let rep = 1; rep < 6; rep++) {
console.log(`Exercise ${exercise}: Lifting weight repetition ${rep} 🏋️♀️`);
}
///////////////////////////////////////
// The while Loop
for (let rep = 1; rep <= 10; rep++) {
console.log(`Lifting weights repetition ${rep} 🏋️♀
️`);
let rep = 1;
while (rep <= 10) {
31
// console.log(`WHILE: Lifting weights repetition ${rep} 🏋️♀
️`);
rep++;
let dice = Math.trunc(Math.random() * 6) + 1;
while (dice !== 6) {
console.log(`You rolled a ${dice}`);
dice = Math.trunc(Math.random() * 6) + 1;
if (dice === 6) console.log('Loop is about to end...');
*/
///////////////////////////////////////
// Coding Challenge #4
/*
Let's improve Steven's tip calculator even more, this time using loops!
1. Create an array 'bills' containing all 10 test bill values
2. Create empty arrays for the tips and the totals ('tips' and 'totals')
3. Use the 'calcTip' function we wrote before (no need to repeat) to calculate tips and total values (bill + tip) for every
bill value in the bills array. Use a for loop to perform the 10 calculations!
TEST DATA: 22, 295, 176, 440, 37, 105, 10, 1100, 86 and 52
HINT: Call calcTip in the loop and use the push method to add values to the tips and totals arrays 😉
4. BONUS: Write a function 'calcAverage' which takes an array called 'arr' as an argument. This function calculates th
e average of all numbers in the given array. This is a DIFFICULT challenge (we haven't done this before)! Here is ho
w to solve it:
4.1. First, you will need to add up all values in the array. To do the addition, start by creating a variable 'sum' that sta
rts at 0. Then loop over the array using a for loop. In each iteration, add the current value to the 'sum' variable. This w
ay, by the end of the loop, you have all values added together
32
4.2. To calculate the average, divide the sum you calculated before by the length of the array (because that's the nu
mber of elements)
4.3. Call the function with the 'totals' array
GOOD LUCK 😀
*/
/*
const calcTip = function (bill) {
return bill >= 50 && bill <= 300 ? bill * 0.15 : bill * 0.2;
const bills = [22, 295, 176, 440, 37, 105, 10, 1100, 86, 52];
const tips = [];
const totals = [];
for (let i = 0; i < bills.length; i++) {
const tip = calcTip(bills[i]);
tips.push(tip);
totals.push(tip + bills[i]);
console.log(bills, tips, totals);
const calcAverage = function (arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
// sum = sum + arr[i];
sum += arr[i];
}
return sum / arr.length;
console.log(calcAverage([2, 3, 7]));
console.log(calcAverage(totals));
console.log(calcAverage(tips));
*/
33
Data Structures, Modern Operators and Strings
'use strict';
const weekdays = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
const openingHours = {
[weekdays[3]]: {
open: 12,
close: 22,
},
[weekdays[4]]: {
open: 11,
close: 23,
},
[weekdays[5]]: {
open: 0, // Open 24 hours
close: 24,
},
};
const restaurant = {
name: 'Classico Italiano',
location: 'Via Angelo Tavanti 23, Firenze, Italy',
categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
mainMenu: ['Pizza', 'Pasta', 'Risotto'],
// ES6 enhanced object literals
openingHours,
order(starterIndex, mainIndex) {
return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
34
},
orderDelivery({ starterIndex = 1, mainIndex = 0, time = '20:00', address }) {
console.log(
`Order received! ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]} will be delivered to $
{address} at ${time}`
);
},
orderPasta(ing1, ing2, ing3) {
console.log(
`Here is your declicious pasta with ${ing1}, ${ing2} and ${ing3}`
);
},
orderPizza(mainIngredient, ...otherIngredients) {
console.log(mainIngredient);
console.log(otherIngredients);
},
};
/*
///////////////////////////////////////
// String Methods Practice
const flights =
'_Delayed_Departure;fao93766109;txl2133758440;11:25+_Arrival;bru0943384722;fao93766109;11:45+_Delayed_A
rrival;hel7439299980;fao93766109;12:05+_Departure;fao93766109;lis2323639855;12:30';
// 🔴 Delayed Departure from FAO to TXL (11h25)
// Arrival from BRU to FAO (11h45)
// 🔴 Delayed Arrival from HEL to FAO (12h05)
35
// Departure from FAO to LIS (12h30)
const getCode = str => str.slice(0, 3).toUpperCase();
for (const flight of flights.split('+')) {
const [type, from, to, time] = flight.split(';');
const output = `${type.startsWith('_Delayed') ? '🔴' : ''}${type.replaceAll(
'_',
' '
)} ${getCode(from)} ${getCode(to)} (${time.replace(':', 'h')})`.padStart(36);
console.log(output);
*/
///////////////////////////////////////
// Coding Challenge #4
/*
Write a program that receives a list of variable names written in underscore_case and convert them to camelCase.
The input will come from a textarea inserted into the DOM (see code below), and conversion will happen when the bu
tton is pressed.
THIS TEST DATA (pasted to textarea)
underscore_case
first_name
Some_Variable
calculate_AGE
delayed_departure
SHOULD PRODUCE THIS OUTPUT (5 separate console.log outputs)
underscoreCase ✅
36
firstName ✅✅
someVariable ✅✅✅
calculateAge ✅✅✅✅
delayedDeparture ✅✅✅✅✅
HINT 1: Remember which character defines a new line in the textarea 😉
HINT 2: The solution only needs to work for a variable made out of 2 words, like a_b
HINT 3: Start without worrying about the ✅. Tackle that only after you have the variable name conversion working 😉
HINT 4: This challenge is difficult on purpose, so start watching the solution in case you're stuck. Then pause and co
ntinue!
Afterwards, test with your own test data!
GOOD LUCK 😀
*/
/*
document.body.append(document.createElement('textarea'));
document.body.append(document.createElement('button'));
document.querySelector('button').addEventListener('click', function () {
const text = document.querySelector('textarea').value;
const rows = text.split('\n');
for (const [i, row] of rows.entries()) {
const [first, second] = row.toLowerCase().trim().split('_');
const output = `${first}${second.replace(
second[0],
second[0].toUpperCase()
)}`;
console.log(`${output.padEnd(20)}${'✅'.repeat(i + 1)}`);
37
}
});
*/
/*
///////////////////////////////////////
// Working With Strings - Part 2
// Split and join
console.log('a+very+nice+string'.split('+'));
console.log('Jonas Schmedtmann'.split(' '));
const [firstName, lastName] = 'Jonas Schmedtmann'.split(' ');
const newName = ['Mr.', firstName, lastName.toUpperCase()].join(' ');
console.log(newName);
const capitalizeName = function (name) {
const names = name.split(' ');
const namesUpper = [];
for (const n of names) {
// namesUpper.push(n[0].toUpperCase() + n.slice(1));
namesUpper.push(n.replace(n[0], n[0].toUpperCase()));
}
console.log(namesUpper.join(' '));
};
capitalizeName('jessica ann smith davis');
capitalizeName('jonas schmedtmann');
// Padding
38
const message = 'Go to gate 23!';
console.log(message.padStart(20, '+').padEnd(30, '+'));
console.log('Jonas'.padStart(20, '+').padEnd(30, '+'));
const maskCreditCard = function (number) {
const str = number + '';
const last = str.slice(-4);
return last.padStart(str.length, '*');
};
console.log(maskCreditCard(64637836));
console.log(maskCreditCard(43378463864647384));
console.log(maskCreditCard('334859493847755774747'));
// Repeat
const message2 = 'Bad waether... All Departues Delayed... ';
console.log(message2.repeat(5));
const planesInLine = function (n) {
console.log(`There are ${n} planes in line ${'🛩'.repeat(n)}`);
};
planesInLine(5);
planesInLine(3);
planesInLine(12);
///////////////////////////////////////
// Working With Strings - Part 2
const airline = 'TAP Air Portugal';
console.log(airline.toLowerCase());
39
console.log(airline.toUpperCase());
// Fix capitalization in name
const passenger = 'jOnAS'; // Jonas
const passengerLower = passenger.toLowerCase();
const passengerCorrect =
passengerLower[0].toUpperCase() + passengerLower.slice(1);
console.log(passengerCorrect);
// Comparing emails
const email = 'hello@jonas.io';
const loginEmail = ' Hello@Jonas.Io \n';
// const lowerEmail = loginEmail.toLowerCase();
// const trimmedEmail = lowerEmail.trim();
const normalizedEmail = loginEmail.toLowerCase().trim();
console.log(normalizedEmail);
console.log(email === normalizedEmail);
// replacing
const priceGB = '288,97£';
const priceUS = priceGB.replace('£', '$').replace(',', '.');
console.log(priceUS);
const announcement =
'All passengers come to boarding door 23. Boarding door 23!';
console.log(announcement.replace('door', 'gate'));
// console.log(announcement.replaceAll('door', 'gate'));
console.log(announcement.replace(/door/g, 'gate'));
// Booleans
40
const plane = 'Airbus A320neo';
console.log(plane.includes('A320'));
console.log(plane.includes('Boeing'));
console.log(plane.startsWith('Airb'));
if (plane.startsWith('Airbus') && plane.endsWith('neo')) {
console.log('Part of the NEW ARirbus family');
// Practice exercise
const checkBaggage = function (items) {
const baggage = items.toLowerCase();
if (baggage.includes('knife') || baggage.includes('gun')) {
console.log('You are NOT allowed on board');
} else {
console.log('Welcome aboard!');
}
};
checkBaggage('I have a laptop, some Food and a pocket Knife');
checkBaggage('Socks and camera');
checkBaggage('Got some snacks and a gun for protection');
///////////////////////////////////////
// Working With Strings - Part 1
const airline = 'TAP Air Portugal';
const plane = 'A320';
console.log(plane[0]);
console.log(plane[1]);
41
console.log(plane[2]);
console.log('B737'[0]);
console.log(airline.length);
console.log('B737'.length);
console.log(airline.indexOf('r'));
console.log(airline.lastIndexOf('r'));
console.log(airline.indexOf('portugal'));
console.log(airline.slice(4));
console.log(airline.slice(4, 7));
console.log(airline.slice(0, airline.indexOf(' ')));
console.log(airline.slice(airline.lastIndexOf(' ') + 1));
console.log(airline.slice(-2));
console.log(airline.slice(1, -1));
const checkMiddleSeat = function (seat) {
// B and E are middle seats
const s = seat.slice(-1);
if (s === 'B' || s === 'E') console.log('You got the middle seat 😬');
else console.log('You got lucky 😎');
};
checkMiddleSeat('11B');
checkMiddleSeat('23C');
checkMiddleSeat('3E');
console.log(new String('jonas'));
console.log(typeof new String('jonas'));
42
console.log(typeof new String('jonas').slice(1));
*/
///////////////////////////////////////
// Coding Challenge #3
/*
Let's continue with our football betting app! This time, we have a map with a log of the events that happened during th
e game. The values are the events themselves, and the keys are the minutes in which each event happened (a footb
all game has 90 minutes plus some extra time).
1. Create an array 'events' of the different game events that happened (no duplicates)
2. After the game has finished, is was found that the yellow card from minute 64 was unfair. So remove this event fro
m the game events log.
3. Print the following string to the console: "An event happened, on average, every 9 minutes" (keep in mind that a ga
me has 90 minutes)
4. Loop over the events and log them to the console, marking whether it's in the first half or second half (after 45 min)
of the game, like this:
[FIRST HALF] 17: ⚽️ GOAL
GOOD LUCK 😀
*/
const gameEvents = new Map([
[17, '⚽️ GOAL'],
[36, '🔁 Substitution'],
[47, '⚽️ GOAL'],
[61, '🔁 Substitution'],
[64, '🔶 Yellow card'],
[69, '🔴 Red card'],
[70, '🔁 Substitution'],
43
[72, '🔁 Substitution'],
[76, '⚽️ GOAL'],
[80, '⚽️ GOAL'],
[92, '🔶 Yellow card'],
]);
/*
// 1.
const events = [...new Set(gameEvents.values())];
console.log(events);
// 2.
gameEvents.delete(64);
// 3.
console.log(
`An event happened, on average, every ${90 / gameEvents.size} minutes`
);
const time = [...gameEvents.keys()].pop();
console.log(time);
console.log(
`An event happened, on average, every ${time / gameEvents.size} minutes`
);
// 4.
for (const [min, event] of gameEvents) {
const half = min <= 45 ? 'FIRST' : 'SECOND';
console.log(`[${half} HALF] ${min}: ${event}`);
*/
/*
44
///////////////////////////////////////
// Maps: Iteration
const question = new Map([
['question', 'What is the best programming language in the world?'],
[1, 'C'],
[2, 'Java'],
[3, 'JavaScript'],
['correct', 3],
[true, 'Correct 🎉'],
[false, 'Try again!'],
]);
console.log(question);
// Convert object to map
console.log(Object.entries(openingHours));
const hoursMap = new Map(Object.entries(openingHours));
console.log(hoursMap);
// Quiz app
console.log(question.get('question'));
for (const [key, value] of question) {
if (typeof key === 'number') console.log(`Answer ${key}: ${value}`);
// const answer = Number(prompt('Your answer'));
const answer = 3;
console.log(answer);
console.log(question.get(question.get('correct') === answer));
// Convert map to array
console.log([...question]);
// console.log(question.entries());
45
console.log([...question.keys()]);
console.log([...question.values()]);
///////////////////////////////////////
// Maps: Fundamentals
const rest = new Map();
rest.set('name', 'Classico Italiano');
rest.set(1, 'Firenze, Italy');
console.log(rest.set(2, 'Lisbon, Portugal'));
rest
.set('categories', ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'])
.set('open', 11)
.set('close', 23)
.set(true, 'We are open :D')
.set(false, 'We are closed :(');
console.log(rest.get('name'));
console.log(rest.get(true));
console.log(rest.get(1));
const time = 8;
console.log(rest.get(time > rest.get('open') && time < rest.get('close')));
console.log(rest.has('categories'));
rest.delete(2);
// rest.clear();
const arr = [1, 2];
rest.set(arr, 'Test');
rest.set(document.querySelector('h1'), 'Heading');
46
console.log(rest);
console.log(rest.size);
console.log(rest.get(arr));
///////////////////////////////////////
// Sets
const ordersSet = new Set([
'Pasta',
'Pizza',
'Pizza',
'Risotto',
'Pasta',
'Pizza',
]);
console.log(ordersSet);
console.log(new Set('Jonas'));
console.log(ordersSet.size);
console.log(ordersSet.has('Pizza'));
console.log(ordersSet.has('Bread'));
ordersSet.add('Garlic Bread');
ordersSet.add('Garlic Bread');
ordersSet.delete('Risotto');
// ordersSet.clear();
console.log(ordersSet);
for (const order of ordersSet) console.log(order);
// Example
47
const staff = ['Waiter', 'Chef', 'Waiter', 'Manager', 'Chef', 'Waiter'];
const staffUnique = [...new Set(staff)];
console.log(staffUnique);
console.log(
new Set(['Waiter', 'Chef', 'Waiter', 'Manager', 'Chef', 'Waiter']).size
);
console.log(new Set('jonasschmedtmann').size);
*/
///////////////////////////////////////
// Coding Challenge #2
/*
Let's continue with our football betting app!
1. Loop over the game.scored array and print each player name to the console, along with the goal number (Example
: "Goal 1: Lewandowski")
2. Use a loop to calculate the average odd and log it to the console (We already studied how to calculate averages, y
ou can go check if you don't remember)
3. Print the 3 odds to the console, but in a nice formatted way, exaclty like this:
Odd of victory Bayern Munich: 1.33
Odd of draw: 3.25
Odd of victory Borrussia Dortmund: 6.5
Get the team names directly from the game object, don't hardcode them (except for "draw"). HINT: Note how the odd
s and the game objects have the same property names 😉
BONUS: Create an object called 'scorers' which contains the names of the players who scored as properties, and the
number of goals as the value. In this game, it will look like this:
{
Gnarby: 1,
48
Hummels: 1,
Lewandowski: 2
}
GOOD LUCK 😀
*/
const game = {
team1: 'Bayern Munich',
team2: 'Borrussia Dortmund',
players: [
[
'Neuer',
'Pavard',
'Martinez',
'Alaba',
'Davies',
'Kimmich',
'Goretzka',
'Coman',
'Muller',
'Gnarby',
'Lewandowski',
],
[
'Burki',
'Schulz',
'Hummels',
'Akanji',
'Hakimi',
'Weigl',
'Witsel',
49
'Hazard',
'Brandt',
'Sancho',
'Gotze',
],
],
score: '4:0',
scored: ['Lewandowski', 'Gnarby', 'Lewandowski', 'Hummels'],
date: 'Nov 9th, 2037',
odds: {
team1: 1.33,
x: 3.25,
team2: 6.5,
},
};
/*
// 1.
for (const [i, player] of game.scored.entries())
console.log(`Goal ${i + 1}: ${player}`);
// 2.
const odds = Object.values(game.odds);
let average = 0;
for (const odd of odds) average += odd;
average /= odds.length;
console.log(average);
// 3.
for (const [team, odd] of Object.entries(game.odds)) {
const teamStr = team === 'x' ? 'draw' : `victory ${game[team]}`;
console.log(`Odd of ${teamStr} ${odd}`);
50
}
// Odd of victory Bayern Munich: 1.33
// Odd of draw: 3.25
// Odd of victory Borrussia Dortmund: 6.5
// BONUS
// So the solution is to loop over the array, and add the array elements as object properties, and then increase the co
unt as we encounter a new occurence of a certain element
const scorers = {};
for (const player of game.scored) {
scorers[player] ? scorers[player]++ : (scorers[player] = 1);
*/
/*
///////////////////////////////////////
// Looping Objects: Object Keys, Values, and Entries
// Property NAMES
const properties = Object.keys(openingHours);
console.log(properties);
let openStr = `We are open on ${properties.length} days: `;
for (const day of properties) {
openStr += `${day}, `;
console.log(openStr);
// Property VALUES
const values = Object.values(openingHours);
console.log(values);
51
// Entire object
const entries = Object.entries(openingHours);
// console.log(entries);
// [key, value]
for (const [day, { open, close }] of entries) {
console.log(`On ${day} we open at ${open} and close at ${close}`);
///////////////////////////////////////
// Optional Chaining
if (restaurant.openingHours && restaurant.openingHours.mon)
console.log(restaurant.openingHours.mon.open);
// console.log(restaurant.openingHours.mon.open);
// WITH optional chaining
console.log(restaurant.openingHours.mon?.open);
console.log(restaurant.openingHours?.mon?.open);
// Example
const days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
for (const day of days) {
const open = restaurant.openingHours[day]?.open ?? 'closed';
console.log(`On ${day}, we open at ${open}`);
// Methods
console.log(restaurant.order?.(0, 1) ?? 'Method does not exist');
52
console.log(restaurant.orderRisotto?.(0, 1) ?? 'Method does not exist');
// Arrays
const users = [{ name: 'Jonas', email: 'hello@jonas.io' }];
// const users = [];
console.log(users[0]?.name ?? 'User array empty');
if (users.length > 0) console.log(users[0].name);
else console.log('user array empty');
///////////////////////////////////////
// The for-of Loop
const menu = [...restaurant.starterMenu, ...restaurant.mainMenu];
for (const item of menu) console.log(item);
for (const [i, el] of menu.entries()) {
console.log(`${i + 1}: ${el}`);
// console.log([...menu.entries()]);
*/
///////////////////////////////////////
// Coding Challenge #1
/*
We're building a football betting app (soccer for my American friends 😅)!
53
Suppose we get data from a web service about a certain game (below). In this challenge we're gonna work with the d
ata. So here are your tasks:
1. Create one player array for each team (variables 'players1' and 'players2')
2. The first player in any player array is the goalkeeper and the others are field players. For Bayern Munich (team 1) c
reate one variable ('gk') with the goalkeeper's name, and one array ('fieldPlayers') with all the remaining 10 field playe
rs
3. Create an array 'allPlayers' containing all players of both teams (22 players)
4. During the game, Bayern Munich (team 1) used 3 substitute players. So create a new array ('players1Final') contai
ning all the original team1 players plus 'Thiago', 'Coutinho' and 'Perisic'
5. Based on the game.odds object, create one variable for each odd (called 'team1', 'draw' and 'team2')
6. Write a function ('printGoals') that receives an arbitrary number of player names (NOT an array) and prints each of
them to the console, along with the number of goals that were scored in total (number of player names passed in)
7. The team with the lower odd is more likely to win. Print to the console which team is more likely to win, WITHOUT
using an if/else statement or the ternary operator.
TEST DATA FOR 6: Use players 'Davies', 'Muller', 'Lewandowski' and 'Kimmich'. Then, call the function again with pl
ayers from game.scored
GOOD LUCK 😀
*/
/*
// 1.
const [players1, players2] = game.players;
console.log(players1, players2);
// 2.
const [gk, ...fieldPlayers] = players1;
console.log(gk, fieldPlayers);
// 3.
54
const allPlayers = [...players1, ...players2];
console.log(allPlayers);
// 4.
const players1Final = [...players1, 'Thiago', 'Coutinho', 'Periscic'];
// 5.
const {
odds: { team1, x: draw, team2 },
} = game;
console.log(team1, draw, team2);
// 6.
const printGoals = function (...players) {
console.log(players);
console.log(`${players.length} goals were scored`);
};
// printGoals('Davies', 'Muller', 'Lewandowski', 'Kimmich');
// printGoals('Davies', 'Muller');
printGoals(...game.scored);
// 7.
team1 < team2 && console.log('Team 1 is more likely to win');
team1 > team2 && console.log('Team 2 is more likely to win');
///////////////////////////////////////
// The Nullish Coalescing Operator
restaurant.numGuests = 0;
const guests = restaurant.numGuests || 10;
console.log(guests);
55
// Nullish: null and undefined (NOT 0 or '')
const guestCorrect = restaurant.numGuests ?? 10;
console.log(guestCorrect);
///////////////////////////////////////
// Short Circuiting (&& and ||)
console.log('---- OR ----');
// Use ANY data type, return ANY data type, short-circuiting
console.log(3 || 'Jonas');
console.log('' || 'Jonas');
console.log(true || 0);
console.log(undefined || null);
console.log(undefined || 0 || '' || 'Hello' || 23 || null);
restaurant.numGuests = 0;
const guests1 = restaurant.numGuests ? restaurant.numGuests : 10;
console.log(guests1);
const guests2 = restaurant.numGuests || 10;
console.log(guests2);
console.log('---- AND ----');
console.log(0 && 'Jonas');
console.log(7 && 'Jonas');
console.log('Hello' && 23 && null && 'jonas');
// Practical example
if (restaurant.orderPizza) {
56
restaurant.orderPizza('mushrooms', 'spinach');
restaurant.orderPizza && restaurant.orderPizza('mushrooms', 'spinach');
///////////////////////////////////////
// Rest Pattern and Parameters
// 1) Destructuring
// SPREAD, because on RIGHT side of =
const arr = [1, 2, ...[3, 4]];
// REST, because on LEFT side of =
const [a, b, ...others] = [1, 2, 3, 4, 5];
console.log(a, b, others);
const [pizza, , risotto, ...otherFood] = [
...restaurant.mainMenu,
...restaurant.starterMenu,
];
console.log(pizza, risotto, otherFood);
// Objects
const { sat, ...weekdays } = restaurant.openingHours;
console.log(weekdays);
// 2) Functions
const add = function (...numbers) {
let sum = 0;
for (let i = 0; i < numbers.length; i++) sum += numbers[i];
console.log(sum);
57
};
add(2, 3);
add(5, 3, 7, 2);
add(8, 2, 5, 3, 2, 1, 4);
const x = [23, 5, 7];
add(...x);
restaurant.orderPizza('mushrooms', 'onion', 'olives', 'spinach');
restaurant.orderPizza('mushrooms');
///////////////////////////////////////
// The Spread Operator (...)
const arr = [7, 8, 9];
const badNewArr = [1, 2, arr[0], arr[1], arr[2]];
console.log(badNewArr);
const newArr = [1, 2, ...arr];
console.log(newArr);
console.log(...newArr);
console.log(1, 2, 7, 8, 9);
const newMenu = [...restaurant.mainMenu, 'Gnocci'];
console.log(newMenu);
// Copy array
const mainMenuCopy = [...restaurant.mainMenu];
58
// Join 2 arrays
const menu = [...restaurant.starterMenu, ...restaurant.mainMenu];
console.log(menu);
// Iterables: arrays, strings, maps, sets. NOT objects
const str = 'Jonas';
const letters = [...str, ' ', 'S.'];
console.log(letters);
console.log(...str);
// console.log(`${...str} Schmedtmann`);
// Real-world example
const ingredients = [
// prompt("Let's make pasta! Ingredient 1?"),
// prompt('Ingredient 2?'),
// prompt('Ingredient 3'),
];
console.log(ingredients);
restaurant.orderPasta(ingredients[0], ingredients[1], ingredients[2]);
restaurant.orderPasta(...ingredients);
// Objects
const newRestaurant = { foundedIn: 1998, ...restaurant, founder: 'Guiseppe' };
console.log(newRestaurant);
const restaurantCopy = { ...restaurant };
restaurantCopy.name = 'Ristorante Roma';
console.log(restaurantCopy.name);
console.log(restaurant.name);
59
///////////////////////////////////////
// Destructuring Objects
restaurant.orderDelivery({
time: '22:30',
address: 'Via del Sole, 21',
mainIndex: 2,
starterIndex: 2,
});
restaurant.orderDelivery({
address: 'Via del Sole, 21',
starterIndex: 1,
});
const { name, openingHours, categories } = restaurant;
console.log(name, openingHours, categories);
const {
name: restaurantName,
openingHours: hours,
categories: tags,
} = restaurant;
console.log(restaurantName, hours, tags);
// Default values
const { menu = [], starterMenu: starters = [] } = restaurant;
console.log(menu, starters);
// Mutating variables
let a = 111;
let b = 999;
const obj = { a: 23, b: 7, c: 14 };
60
({ a, b } = obj);
console.log(a, b);
// Nested objects
const {
fri: { open: o, close: c },
} = openingHours;
console.log(o, c);
///////////////////////////////////////
// Destructuring Arrays
const arr = [2, 3, 4];
const a = arr[0];
const b = arr[1];
const c = arr[2];
const [x, y, z] = arr;
console.log(x, y, z);
console.log(arr);
let [main, , secondary] = restaurant.categories;
console.log(main, secondary);
// Switching variables
// const temp = main;
// main = secondary;
// secondary = temp;
// console.log(main, secondary);
[main, secondary] = [secondary, main];
console.log(main, secondary);
61
// Receive 2 return values from a function
const [starter, mainCourse] = restaurant.order(2, 0);
console.log(starter, mainCourse);
// Nested destructuring
const nested = [2, 4, [5, 6]];
// const [i, , j] = nested;
const [i, , [j, k]] = nested;
console.log(i, j, k);
// Default values
const [p = 1, q = 1, r = 1] = [8, 9];
console.log(p, q, r);
*/
62
Closer look function
'use strict';
/*
///////////////////////////////////////
// Default Parameters
const bookings = [];
const createBooking = function (
flightNum,
numPassengers = 1,
price = 199 * numPassengers
) {
// ES5
// numPassengers = numPassengers || 1;
// price = price || 199;
const booking = {
flightNum,
numPassengers,
price,
};
console.log(booking);
bookings.push(booking);
};
createBooking('LH123');
createBooking('LH123', 2, 800);
createBooking('LH123', 2);
createBooking('LH123', 5);
createBooking('LH123', undefined, 1000);
63
///////////////////////////////////////
// How Passing Arguments Works: Values vs. Reference
const flight = 'LH234';
const jonas = {
name: 'Jonas Schmedtmann',
passport: 24739479284,
};
const checkIn = function (flightNum, passenger) {
flightNum = 'LH999';
passenger.name = 'Mr. ' + passenger.name;
if (passenger.passport === 24739479284) {
alert('Checked in');
} else {
alert('Wrong passport!');
}
};
// checkIn(flight, jonas);
// console.log(flight);
// console.log(jonas);
// Is the same as doing...
// const flightNum = flight;
// const passenger = jonas;
const newPassport = function (person) {
person.passport = Math.trunc(Math.random() * 100000000000);
};
newPassport(jonas);
checkIn(flight, jonas);
64
///////////////////////////////////////
// Functions Accepting Callback Functions
const oneWord = function (str) {
return str.replace(/ /g, '').toLowerCase();
};
const upperFirstWord = function (str) {
const [first, ...others] = str.split(' ');
return [first.toUpperCase(), ...others].join(' ');
};
// Higher-order function
const transformer = function (str, fn) {
console.log(`Original string: ${str}`);
console.log(`Transformed string: ${fn(str)}`);
console.log(`Transformed by: ${fn.name}`);
};
transformer('JavaScript is the best!', upperFirstWord);
transformer('JavaScript is the best!', oneWord);
// JS uses callbacks all the time
const high5 = function () {
console.log('👋');
};
document.body.addEventListener('click', high5);
['Jonas', 'Martha', 'Adam'].forEach(high5);
///////////////////////////////////////
// Functions Returning Functions
65
const greet = function (greeting) {
return function (name) {
console.log(`${greeting} ${name}`);
};
};
const greeterHey = greet('Hey');
greeterHey('Jonas');
greeterHey('Steven');
greet('Hello')('Jonas');
// Challenge
const greetArr = greeting => name => console.log(`${greeting} ${name}`);
greetArr('Hi')('Jonas');
///////////////////////////////////////
// The call and apply Methods
const lufthansa = {
airline: 'Lufthansa',
iataCode: 'LH',
bookings: [],
// book: function() {}
book(flightNum, name) {
console.log(
`${name} booked a seat on ${this.airline} flight ${this.iataCode}${flightNum}`
);
this.bookings.push({ flight: `${this.iataCode}${flightNum}`, name });
},
};
66
lufthansa.book(239, 'Jonas Schmedtmann');
lufthansa.book(635, 'John Smith');
const eurowings = {
airline: 'Eurowings',
iataCode: 'EW',
bookings: [],
};
const book = lufthansa.book;
// Does NOT work
// book(23, 'Sarah Williams');
// Call method
book.call(eurowings, 23, 'Sarah Williams');
console.log(eurowings);
book.call(lufthansa, 239, 'Mary Cooper');
console.log(lufthansa);
const swiss = {
airline: 'Swiss Air Lines',
iataCode: 'LX',
bookings: [],
};
book.call(swiss, 583, 'Mary Cooper');
// Apply method
const flightData = [583, 'George Cooper'];
67
book.apply(swiss, flightData);
console.log(swiss);
book.call(swiss, ...flightData);
///////////////////////////////////////
// The bind Method
// book.call(eurowings, 23, 'Sarah Williams');
const bookEW = book.bind(eurowings);
const bookLH = book.bind(lufthansa);
const bookLX = book.bind(swiss);
bookEW(23, 'Steven Williams');
const bookEW23 = book.bind(eurowings, 23);
bookEW23('Jonas Schmedtmann');
bookEW23('Martha Cooper');
// With Event Listeners
lufthansa.planes = 300;
lufthansa.buyPlane = function () {
console.log(this);
this.planes++;
console.log(this.planes);
};
// lufthansa.buyPlane();
document
.querySelector('.buy')
.addEventListener('click', lufthansa.buyPlane.bind(lufthansa));
68
// Partial application
const addTax = (rate, value) => value + value * rate;
console.log(addTax(0.1, 200));
const addVAT = addTax.bind(null, 0.23);
// addVAT = value => value + value * 0.23;
console.log(addVAT(100));
console.log(addVAT(23));
const addTaxRate = function (rate) {
return function (value) {
return value + value * rate;
};
};
const addVAT2 = addTaxRate(0.23);
console.log(addVAT2(100));
console.log(addVAT2(23));
*/
///////////////////////////////////////
// Coding Challenge #1
/*
Let's build a simple poll app!
A poll has a question, an array of options from which people can choose, and an array with the number of replies for
each option. This data is stored in the starter object below.
Here are your tasks:
69
1. Create a method called 'registerNewAnswer' on the 'poll' object. The method does 2 things:
1.1. Display a prompt window for the user to input the number of the selected option. The prompt should look like thi
s:
What is your favourite programming language?
0: JavaScript
1: Python
2: Rust
3: C++
(Write option number)
1.2. Based on the input number, update the answers array. For example, if the option is 3, increase the value AT PO
SITION 3 of the array by 1. Make sure to check if the input is a number and if the number makes sense (e.g answer 5
2 wouldn't make sense, right?)
2. Call this method whenever the user clicks the "Answer poll" button.
3. Create a method 'displayResults' which displays the poll results. The method takes a string as an input (called 'typ
e'), which can be either 'string' or 'array'. If type is 'array', simply display the results array as it is, using console.log().
This should be the default option. If type is 'string', display a string like "Poll results are 13, 2, 4, 1".
4. Run the 'displayResults' method at the end of each 'registerNewAnswer' method call.
HINT: Use many of the tools you learned about in this and the last section 😉
BONUS: Use the 'displayResults' method to display the 2 arrays in the test data. Use both the 'array' and the 'string' o
ption. Do NOT put the arrays in the poll object! So what shoud the this keyword look like in this situation?
BONUS TEST DATA 1: [5, 2, 3]
BONUS TEST DATA 2: [1, 5, 3, 9, 6, 1]
GOOD LUCK 😀
*/
/*
const poll = {
70
question: 'What is your favourite programming language?',
options: ['0: JavaScript', '1: Python', '2: Rust', '3: C++'],
// This generates [0, 0, 0, 0]. More in the next section 😃
answers: new Array(4).fill(0),
registerNewAnswer() {
// Get answer
const answer = Number(
prompt(
`${this.question}\n${this.options.join('\n')}\n(Write option number)`
)
);
console.log(answer);
// Register answer
typeof answer === 'number' &&
answer < this.answers.length &&
this.answers[answer]++;
this.displayResults();
this.displayResults('string');
},
displayResults(type = 'array') {
if (type === 'array') {
console.log(this.answers);
} else if (type === 'string') {
// Poll results are 13, 2, 4, 1
console.log(`Poll results are ${this.answers.join(', ')}`);
}
},
};
71
document
.querySelector('.poll')
.addEventListener('click', poll.registerNewAnswer.bind(poll));
poll.displayResults.call({ answers: [5, 2, 3] }, 'string');
poll.displayResults.call({ answers: [1, 5, 3, 9, 6, 1] }, 'string');
poll.displayResults.call({ answers: [1, 5, 3, 9, 6, 1] });
// [5, 2, 3]
// [1, 5, 3, 9, 6, 1]
///////////////////////////////////////
// Immediately Invoked Function Expressions (IIFE)
const runOnce = function () {
console.log('This will never run again');
};
runOnce();
// IIFE
(function () {
console.log('This will never run again');
const isPrivate = 23;
})();
// console.log(isPrivate);
(() => console.log('This will ALSO never run again'))();
const isPrivate = 23;
var notPrivate = 46;
72
}
// console.log(isPrivate);
console.log(notPrivate);
///////////////////////////////////////
// Closures
const secureBooking = function () {
let passengerCount = 0;
return function () {
passengerCount++;
console.log(`${passengerCount} passengers`);
};
};
const booker = secureBooking();
booker();
booker();
booker();
console.dir(booker);
///////////////////////////////////////
// More Closure Examples
// Example 1
let f;
const g = function () {
const a = 23;
73
f = function () {
console.log(a * 2);
};
};
const h = function () {
const b = 777;
f = function () {
console.log(b * 2);
};
};
g();
f();
console.dir(f);
// Re-assigning f function
h();
f();
console.dir(f);
// Example 2
const boardPassengers = function (n, wait) {
const perGroup = n / 3;
setTimeout(function () {
console.log(`We are now boarding all ${n} passengers`);
console.log(`There are 3 groups, each with ${perGroup} passengers`);
}, wait * 1000);
console.log(`Will start boarding in ${wait} seconds`);
};
74
const perGroup = 1000;
boardPassengers(180, 3);
*/
///////////////////////////////////////
// Coding Challenge #2
/*
This is more of a thinking challenge than a coding challenge 🤓
Take the IIFE below and at the end of the function, attach an event listener that changes the color of the selected h1
element ('header') to blue, each time the BODY element is clicked. Do NOT select the h1 element again!
And now explain to YOURSELF (or someone around you) WHY this worked! Take all the time you need. Think about
WHEN exactly the callback function is executed, and what that means for the variables involved in this example.
GOOD LUCK 😀
*/
/*
(function () {
const header = document.querySelector('h1');
header.style.color = 'red';
document.querySelector('body').addEventListener('click', function () {
header.style.color = 'blue';
});
})();
*/
75
76