02 JavaScript Language Basics
02 JavaScript Language Basics
console.log(firstName);
console.log(fullAge);
var job;
console.log(job);
job = 'Teacher';
console.log(job);
var if = 23;
****************************
Variable mutation and type coercion
var firstName = 'John';
// Type coercion
job = 'teacher';
isMarried = false;
console.log(firstName + ' is a ' + age + ' year old ' + job + '. Is he married? ' +
isMarried);
// Variable mutation
age = 'twenty eight';
job = 'driver';
alert(firstName + ' is a ' + age + ' year old ' + job + '. Is he married? ' + isMarried);
****************************
Basic operators
var year, yearJohn, yearMark;
now = 2018;
ageJohn = 28;
ageMark = 33;
// Math operators
yearJohn = now - ageJohn;
console.log(yearJohn);
console.log(now + 2);
console.log(now * 2);
console.log(now / 10);
// Logical operators
var johnOlder = ageJohn < ageMark;
console.log(johnOlder);
// typeof operator
console.log(typeof johnOlder);
console.log(typeof ageJohn);
var x;
console.log(typeof x);
****************************
Operator precedence
var now = 2018;
// Multiple operators
var isFullAge = now - yearJohn >= fullAge; // true
console.log(isFullAge);
// Grouping
var ageJohn = now - yearJohn;
console.log(average);
// Multiple assignments
var x, y;
x = y = (3 + 5) * 4 - 6; // 8 * 4 - 6 // 32 - 6 // 26
console.log(x, y);
// More operators
x *= 2;
console.log(x);
x += 10;
console.log(x);
x--;
console.log(x);
****************************
CODING CHALLENGE 1
Mark and John are trying to compare their BMI (Body Mass Index), which is calculated using
tformula: BMI = mass / height^2 = mass / (height * height). (mass in kg and height in meter).
3. Create a boolean variable containing information about whether Mark has a higher BMI
thanJohn.
4. Print a string to the console containing the variable from step 3. (Something like "Is
Mark's BMI higher than John's? true").
GOOD LUCK 😀
console.log(BMIMark, BMIJohn);
} else {
if (isMarried) {
} else {
} else {
}
****************************
Boolean logic
var firstName = 'John';
} else {
}
****************************
The Ternary Operator and Switch Statements
var firstName = 'John';
// Ternary operator
age >= 18 ? console.log(firstName + ' drinks beer.') : console.log(firstName + ' drinks
juice.');
console.log(drink);
} else {
// Switch statement
var job = 'instructor';
switch (job) {
case 'teacher':
case 'instructor':
break;
case 'driver':
console.log(firstName + ' drives an uber in Lisbon.');
break;
case 'designer':
break;
default:
age = 56;
switch (true) {
break;
break;
break;
default:
}
****************************
Truthy and Falsy values and equality
operators
// falsy values: undefined, null, 0, '', NaN
var height;
height = 23;
console.log('Variable is defined');
} else {
// Equality operators
if (height === '23') {
}
****************************
CODING CHALLENGE 2
John and Mike both play basketball in different teams. In the latest 3 games, John's team
scored 89, 120 and 103 points, while Mike's team scored 116, 94 and 123 points.
2. Decide which teams wins in average (highest average score), and print the winner to the
console. Also include the average score in the output.
3. Then change the scores to show different winners. Don't forget to take into account
theremight be a draw (the same average score)
4. EXTRA: Mary also plays basketball, and her team scored 97, 134 and 105 points. Like
beforlog the average winner to the console. HINT: you will need the && operator to take the
decision. If you can't solve this one, just watch the solution, it's no problem :)
5. Like before, change the scores to generate different winners, keeping in mind there mightbe
draws.
GOOD LUCK 😀
} else {
console.log('There is a draw');
} else {
console.log('There is a draw');
}
****************************
Functions
function calculateAge(birthYear) {
if (retirement > 0) {
} else {
}
}
yearsUntilRetirement(1990, 'John');
yearsUntilRetirement(1948, 'Mike');
yearsUntilRetirement(1969, 'Jane');
****************************
Function Statements and Expressions
// Function declaration
// Function expression
switch(job) {
case 'teacher':
case 'driver':
case 'designer':
default:
console.log(whatDoYouDo('teacher', 'John'));
console.log(whatDoYouDo('designer', 'Jane'));
console.log(whatDoYouDo('retired', 'Mark'));
****************************
Arrays
// Initialize new array
var names = ['John', 'Mark', 'Jane'];
console.log(names[2]);
console.log(names.length);
names[names.length] = 'Mary';
console.log(names);
john.push('blue');
john.unshift('Mr.');
console.log(john);
john.pop();
john.pop();
john.shift();
console.log(john);
console.log(john.indexOf(23));
var isDesigner = john.indexOf('designer') === -1 ? 'John is NOT a designer' : 'John IS a
designer';
console.log(isDesigner);
****************************
CODING CHALLENGE 3
John and his family went on a holiday and went to 3 different restaurants. The bills were
$124, $48 and $268.
To tip the waiter a fair amount, John created a simple tip calculator (as a function). He
likes to tip 20% of the bill when the bill is less than $50, 15% when the bill is between
$5and $200, and 10% if the bill is more than $200.
GOOD LUCK 😀
function tipCalculator(bill) {
var percentage;
percentage = .2;
percentage = .15;
} else {
percentage = .1;
}
return percentage * bill;
tipCalculator(bills[1]),
tipCalculator(bills[2])];
bills[1] + tips[1],
bills[2] + tips[2]];
console.log(tips, finalValues);
****************************
Objects and properties
// Object literal
var john = {
firstName: 'John',
lastName: 'Smith',
birthYear: 1990,
job: 'teacher',
isMarried: false
};
console.log(john.firstName);
console.log(john['lastName']);
var x = 'birthYear';
console.log(john[x]);
john.job = 'designer';
john['isMarried'] = true;
console.log(john);
firstName: 'John',
lastName: 'Smith',
birthYear: 1992,
job: 'teacher',
isMarried: false,
calcAge: function() {
};
john.calcAge();
console.log(john);
****************************
CODING CHALLENGE 4
Let's remember the first coding challenge where Mark and John compared their BMIs. Let's
nowimplement the same functionality with objects and methods.
1. For each of them, create an object with properties for their full name, mass, and height
2. Then, add a method to each object to calculate the BMI. Save the BMI to the object and
alreturn it from the method.
3. In the end, log to the console who has the highest BMI, together with the full name and
trespective BMI. Don't forget they might have the same BMI.
Remember: BMI = mass / height^2 = mass / (height * height). (mass in kg and height in meter)
GOOD LUCK 😀
var john = {
mass: 110,
height: 1.95,
calcBMI: function() {
return this.bmi;
var mark = {
mass: 78,
height: 1.69,
calcBMI: function() {
return this.bmi;
} else {
}
****************************
Loops and iteration
// for loop
for (var i = 1; i <= 20; i += 2) {
console.log(i);
//...
console.log(john[i]);
// While loop
var i = 0;
console.log(john[i]);
i++;
}
// continue and break statements
var john = ['John', 'Smith', 1990, 'designer', false, 'blue'];
console.log(john[i]);
console.log(john[i]);
// Looping backwards
for (var i = john.length - 1; i >= 0; i--) {
console.log(john[i]);
}
****************************
CODING CHALLENGE 5
Remember the tip calculator challenge? Let's create a more advanced version using everythingwe
learned!
This time, John and his family went to 5 different restaurants. The bills were $124, $48,
$268, $180 and $42.
John likes to tip 20% of the bill when the bill is less than $50, 15% when the bill is
betwe$50 and $200, and 10% if the bill is more than $200.
3. This method should include a loop to iterate over all the paid bills and do the tip
calculations
4. As an output, create 1) a new array containing all tips, and 2) an array containing
finalpaid amounts (bill + tip). HINT: Start with two empty arrays [] as properties and then
fill them up in the loop.
EXTRA AFTER FINISHING: Mark's family also went on a holiday, going to 4 different
restaurantThe bills were $77, $375, $110, and $45.
Mark likes to tip 20% of the bill when the bill is less than $100, 10% when the bill is
between $100 and $300, and 25% if the bill is more than $300 (different than John).
5. Implement the same functionality as before, this time using Mark's tipping rules
6. Create a function (not a method) to calculate the average of a given array of tips.
HINT:Loop over the array, and in each iteration store the current sum in a variable (starting
fro0). After you have the sum of the array, divide it by the number of elements in it (that's
hyou calculate the average)
7. Calculate the average tip for each family
8. Log to the console which family paid the highest tips on average
GOOD LUCK 😀
var john = {
calcTips: function() {
this.tips = [];
this.finalValues = [];
percentage = .2;
percentage = .15;
} else {
percentage = .1;
calcTips: function() {
this.tips = [];
this.finalValues = [];
percentage = .2;
percentage = .1;
} else {
percentage = .25;
function calcAverage(tips) {
var sum = 0;
// Do the calculations
john.calcTips();
mark.calcTips();
john.average = calcAverage(john.tips);
mark.average = calcAverage(mark.tips);
console.log(john, mark);