JS-Dev-101 practice question 17 of 25

Refer to the code below: flag(); function flag() { console.log('flag'); } const anotherFlag = () => { console.log('another flag'); } anotherFlag(); What is result of the code block?

Full set: 148 questions
Answer options
A: The console logs only 'flag'.
B: An error is thrown.
C: The console logs 'flag' and then an error is thrown.
D: The console logs 'flag' and 'another flag'. Correct answer
Correct Answer:
D. The console logs 'flag' and 'another flag'.
Explanation

The code executes successfully and logs both 'flag' and 'another flag'. The function declaration flag() is hoisted, meaning its definition is moved to the top of its scope before code execution. Therefore, it can be called before it is declared. The anotherFlag variable is a const assigned an arrow function. While the const declaration is hoisted, it is not initialized and remains in a "temporal dead zone" until the assignment line. Since anotherFlag() is called after its declaration and assignment, it executes without error.

Why Incorrect

A. The console logs only 'flag': This is incorrect because the call to anotherFlag() is valid and will execute after its definition.
B. An error is thrown: No error is thrown because the function declaration flag is hoisted and anotherFlag is called after its initialization.
C. The console logs 'flag' and then an error is thrown: This is incorrect. The call to anotherFlag() is valid as it occurs after the line where it is defined and initialized.

References

MDN Web Docs, "Hoisting", JavaScript Guide. Explains that "Function declarations are hoisted completely," while let and const declarations are hoisted but not initialized.

MDN Web Docs, "Functions", JavaScript Guide, "Function declarations". Describes how function declarations are loaded before any code is executed.

Flanagan, D. (2020). JavaScript: The Definitive Guide (7th ed.). O'Reilly Media. Chapter 3 discusses the hoisting behavior of var, let, const, and function declarations.

Scroll to Top