Activating Strict Mode
use it at the beginning of each script to write more secure code
strict mode introduce bugs into our code: forbid us to do certain things; it creates visible errors on the developer console, where in other situations, JS will just fail silently.
'use strict';
let hasDriversLicense = false;
const passTest = true;
if (passTest) hasDriversLicense = true;
if (hasDriversLicense) console.log('I can drive :D');
// reserved word: interface
const interface = 'Audio';
const private = 223;
Functions
// reuse a piece of code
function logger() {
console.log('My name is Jonas');
}
// invoking / running / calling the function
logger();
logger();
logger();
// receive data and return data back
// parameters形参
function fruitProcessor(apples, oranges) {
// console.log(apples, oranges);
const juice = `Juice with ${apples} apples and ${oranges} oranges.`
return juice;
}
// arguments实参
const appleJuice = fruitProcessor(5, 0);
console.log(appleJuice);
// console.log(fruitProcessor(5, 0));
const appleOrangeJuice = fruitProcessor(2, 4);
console.log(appleOrangeJuice);
const num = Number('23');
Function Declarations VS. Expressions
Difference:
We can call the function declarations before they are defined in the code.
Functions are actually just values as a number, a string or a boolean value. Function is not a type like a String or Number type.
// function declarations: use 'funtion' keyword to declare a function
//hoisting
const age1 = calcAge1(1991);
function calcAge1(birthYear) {
return 2037 - birthYear;
}
// function expression (an anonymous function)
const calcAge2 = function (birthYear) {
return 2037 - birthYear;
}
const age2 = calcAge2(1991);
console.log(age1, age2);
paremeter VS. argument
parameter: the kind of placeholder in the function
argument: the actual value that we use to fill in that placeholder
Arrow Functions(箭头函数)
simply a special form of function expression that is shorter
excellent for simple one-liner functions
arrow functions do not get a so-called ‘this’ keyword.
// Arrow function (a special form of function expression)
const calcAge3 = birthYear => 2037 - birthYear;
const age3 = calcAge3(1991);
console.log(age3);
const yearsUntilRetirement = (birthYear, firstName) => {
const age = 2037 - birthYear;
const retirement = 65 - age;
// return retirement;
return `${firstName} retires in ${retirement} years.`
}
console.log(yearsUntilRetirement(1991, 'Jonas'));
console.log(yearsUntilRetirement(1980, 'Bob'));
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} pieces of apple and ${orangePieces} pieces of apple orange.`
return juice;
}
console.log(fruitProcessor(2, 3));
Functions Review
Introduction to Arrays
data structure in JS: Arrays and Objects
An Array is like a big container into which we can throw variables and then later reference them.
const friend1 = 'Michael';
const friend2 = 'Steven';
const friend3 = 'Peter';
// literal syntax
const friends = ['Michael', 'Steven', 'Peter'];
console.log(friends);
const years = new Array(1991, 1984, 2008, 2020);
// use square bracket syntax for retrieving elements from the Array
console.log(friends[0]);
console.log(friends[2]);
// length: a property
console.log(friends.length);
// use length to automatically get the last element of any Array
console.log(friends[friends.length - 1]);
// use square bracket syntax for adding elements to the Array
// We cannot change a variable declared with const, but can change one element of the Array. The primitive values are immutable, but an Array is not a primitive value.
friends[2] = 'Jay';
console.log(friends);
// we cannot replace the entire Array
friends = ['Bob', 'Alice'];
// A array can hold values with different types
const firstName = 'Jonas';
const jonas = [firstName, 'Schmedtmann', 2037 - 1991, 'teacher', friends];
console.log(jonas);
console.log(jonas.length);
Basic Array Operations (Methods)
const friends = ['Michael', 'Steven', 'Peter'];
// push(): a method that adds elements to the end of an array, and returns the length of the new array
const newLength = friends.push('Jay');
console.log(friends);
console.log(newLength);
// unshift(): adds elements to the beginning of the array, and also returns the length of the new array
friends.unshift('John')
console.log(friends);
// pop(): remove elements the last element of the array, which is opposite to the push(), and returns the removed element
const popped = friends.pop();
console.log(popped);
console.log(friends);
// shift(): remove elements the first element of the array, which is opposite to the unshift(), and returns the removed element
friends.shift();
console.log(friends);
// indexOf(): tell us in which position a certain elements is in the array, return the index at which this element is located or -1 for an element that is not in there
// ===
console.log(friends.indexOf('Steven'));
console.log(friends.indexOf('Bob'));
// includes(): return true if the element is in the array or false if it is not
console.log(friends.includes('Steven'));
console.log(friends.includes('Bob'));
// === strict equality
friends.push(23);
console.log(friends.includes('23'));
console.log(friends.indexOf('23'));
if (friends.includes('Peter')) {
console.log('You have a friend called Peter');
}
Introduction to Objects
In Objects, we actually define key value pairs.
use arrays for more ordered data and objects for more unstructured data.
const jonasArray = [
'Jonas',
'Schmedtmann',
2037 - 1991,
'teacher',
['Michael', 'Peter', 'Steven']
];
// key-value pairs, each of these keys is also called a property
// object literal syntax
const jonas = {
firstName: 'Jonas',
lastName: 'Schmedtmann',
age: 2037 - 1991,
job: 'teacher',
friend: ['Michael', 'Peter', 'Steven']
};
Dot VS. Bracket Notation
the ways to retrieve data from objects and change data in objects
const jonas = {
firstName: 'Jonas',
lastName: 'Schmedtmann',
age: 2037 - 1991,
job: 'teacher',
friends: ['Michael', 'Peter', 'Steven']
};
console.log(jonas);
// dot notation: this dot is an operator
console.log(jonas.lastName);
// bracket notation: we can put any expression here
console.log(jonas['lastName']);
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 firends');
console.log(jonas[interestedIn]);
// we will get undefined when we try to access a property on an object that does not exist
console.log(jonas.interestedIn);
// if (jonas[interestedIn]) {
// console.log(jonas[interestedIn]);
// } else {
// console.log('Wrong request! ')
// }
jonas.location = 'Portugal';
jonas['twitter'] = '@jonas';
console.log(jonas);
console.log(`${jonas.firstName} has ${jonas.friends.length} friends, and his best friend is called ${jonas.friends[0]}`);
Object Methods
// add functions to objects
const jonas = {
firstName: 'Jonas',
lastName: 'Schmedtmann',
birthYear: 1991,
job: 'teacher',
friends: ['Michael', 'Peter', 'Steven'],
hasDirversLicense: true,
// any function attached to an object is called a method
// calcAge: function (birthYear) {
// return 2037 - birthYear;
// }
// 'this' keyword: basically equal to the object on which the method is called
// calcAge: function () {
// // console.log(this);
// return 2037 - this.birthYear;
// }
// if we don't call the calcAge, then the age property would not exist
calcAge: function () {
this.age = 2037 - this.birthYear;
return this.age;
},
getSummary: function () {
return `${this.firstName} is a ${this.calcAge()}-year old ${this.job}, and he has ${this.hasDirversLicense ? 'a' : 'no'} driver's license`;
}
};
console.log(jonas.calcAge());
console.log(jonas.age); // 必须要先调用calcAge()
// console.log(jonas['calcAge'](1991));
console.log(jonas.getSummary());
the arrays are actually also objects, a special kind of object. Their functions like pop, push, shift and unshift…
Iteration: The For Loop
for (let rep = 1; rep <= 10; rep++) {
console.log(`Lifting weights repeatition ${rep} 🏋️♀️`);
}
Looping Arrays, Breaking and Continuing
const jonasArray = [
'Jonas',
'Schmedtmann',
2037 - 1991,
'teacher',
['Michael', 'Peter', 'Steven'],
true
];
const types = [];
for (let i = 0; i < jonasArray.length; i++) {
console.log(jonasArray[i], typeof jonasArray[i]);
// Filling types array
// types[i] = typeof jonasArray[i];
types.push(typeof jonasArray[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
// continue: exit the current iteration of the loop and continue to the next
// break: completely terminate the whole loop
console.log('--- ONLY STRINGS ---');
for (let i = 0; i < jonasArray.length; i++) {
// only log strings to the console
if (typeof jonasArray[i] !== 'string') continue;
console.log(jonasArray[i], typeof jonasArray[i]);
}
console.log('--- BREAK WITH NUMBER ---')
for (let i = 0; i < jonasArray.length; i++) {
if (typeof jonasArray[i] === 'number') break;
console.log(jonasArray[i], typeof jonasArray[i]);
}
Looping Backwards and Loops In Loops
const jonasArray = [
'Jonas',
'Schmedtmann',
2037 - 1991,
'teacher',
['Michael', 'Peter', 'Steven']
];
for (let i = jonasArray.length - 1; i >= 0; i--) {
console.log(i, jonasArray[i]);
}
for (let exercise = 1; exercise < 4; exercise++) {
console.log(`-----Starting exetcise ${exercise}`);
for (let rep = 1; rep < 6; rep++) {
console.log(`Exercise ${exercise}: Lifting weights repeatition ${rep} 🏋️♀️`);
}
}
The While Loop
for (let rep = 1; rep <= 10; rep++) {
console.log(`FOR: Lifting weights repeatition ${rep} 🏋️♀️`);
}
let rep = 1;
while (rep <= 10) {
console.log(`WHILE: Lifting weights repeatition ${rep} 🏋️♀️`);
rep++;
}
// Math.random()会返回一个位于区间[0, 1)的数,*6之后位于[0, 6)之间
// Math.trunc()去除小数部分
let dice = Math.trunc(Math.random() * 6) + 1;
// while loop does not have to depend on any counter variable
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...');
}