Search⌘ K

Exercise on Function Scope, Block Scope, Constants

Explore ES6 improvements on function and block scope along with constants by working through code exercises. Learn to predict console outputs, modify code without changing logging statements, and deepen your understanding of JavaScript scope rules and constants management.

We'll cover the following...

Exercise 1

Check the following code snippet riddle:

Determine the values logged to the console before you execute it.

Node.js
'use strict';
var guessMe1 = 1;
let guessMe2 = 2;
{
try {
console.log( guessMe1, guessMe2 ); // (A)
} catch(err) {
console.log("Error");
}
let guessMe2 = 3;
console.log( guessMe1, guessMe2 ); // (B)
}
console.log( guessMe1, guessMe2 ); // (C)
const print_func = () => {
console.log( guessMe1 ); // (D)
var guessMe1 = 5;
let guessMe2 = 6;
console.log( guessMe1, guessMe2 ); // (E)
};
console.log( guessMe1, guessMe2 ); // (F)

Explanation

The output in the console will be as follows:

guessMe1 and/or guessMe2 not defined
1 3
1 2
1 2

Let’s examine the six console logs one by one.

(A): Here, guessMe1 holds the value original value of 1 as it has not been defined again in the ...