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 questionsThe 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.
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.
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.
Keep practicing
Take the free JS-Dev-101 practice test
Ten exam-style questions with answers and explanations, plus the exam facts and study guides.
More questions
Other JS-Dev-101 practice questions
- Question 1A developer executes: document.cookie; document.cookie = 'key=John Smith'; What is the be…
- Question 2A developer is required to write a function that calculates the sum of elements in an arr…
- Question 3Given the code below: 01 const delay = async delay => { 02 return new Promise((resolve, r…
- Question 401 function Animal(size, type) { 02 this.type = type || 'Animal'; 03 this.canTalk = false…
- Question 5Refer to the code snippet: 01 let array = [1, 2, 3, 4, 4, 5, 4, 4]; 02 for (let i = 0; i …
- Question 6Code: 01 let array = [1, 2, 3, 4, 4, 5, 4, 4]; 02 for (let i = 0; i < array.length; i++) …
