For each exercise, tell me in what order each of the logs are executed, and what each of them will actually log.
In order to complete these exercises, you must understand the following concepts:
- hoisting
- variable assignment/reassignment vs. variable declaration
- the three scoping levels: global, functional and block
- the scoping levels that var/let/const adhere to
- the order in which JavaScript is read and executed
let num = 10;
function foo() {
if (num > 5) {
num = 7;
}
console.log('A:', num);
}
foo();
console.log('B: ', num);
Bonus Challenges:
- What would happen if we changed
let
toconst
? - What would happen if we added
var
in front ofnum = 7
?
let grade = 100;
function losePoints() {
grade = 90;
function addPoints() {
const grade = 95;
if (grade === 95) {
let grade = 97;
}
console.log('A: ', grade);
}
addPoints();
console.log('B: ', grade);
}
losePoints();
console.log('C: ', grade);
var num = 5;
function first() {
console.log('A: ', num);
num = 6;
console.log('B: ', num);
}
function second() {
console.log('C: ', num);
let num = 7;
}
first();
second();
console.log('D: ', num);
var instructor = 'Pam';
function changeInstructor() {
console.log('A: ', instructor);
if (instructor === 'Brittany') {
const instructor = 'Nathaniel';
} else {
let instructor = 'Brittany';
}
console.log('B: ', instructor);
function rename() {
instructor = 'Louisa';
console.log('C: ', instructor);
}
rename();
console.log('D: ', instructor);
}
console.log('E: ', instructor);
changeInstructor();
console.log('F: ', instructor);
var shoe = 'flipflop';
function putOnShoe() {
console.log('A: ', shoe);
var shoe = 'boot';
}
console.log('B: ', shoe);
putOnShoe();
console.log('C: ', shoe);