Unit 3 - Practice Quiz
1 What is created whenever a function is invoked in JavaScript?
2 What is the primary purpose of the scope chain?
3 What is a closure in JavaScript?
4
In the following code, what feature allows the inner function to access the outerVar variable?
javascript
function outer() {
let outerVar = 'hello';
function inner() {
console.log(outerVar);
}
return inner;
}
const myFunc = outer();
myFunc(); // logs 'hello'
5 In JavaScript, what is the mechanism that allows objects to inherit properties and methods from other objects?
6 What is at the very end of every prototype chain?
undefined value
{}
window object
null value
7
If you add a method to Array.prototype, what is the result?
Array object itself.
8 What is the primary role of the Event Loop in JavaScript?
9 JavaScript is described as a single-threaded language. What does this mean?
10 A JavaScript Promise can be in one of three states. What are they?
started, running, or finished
async, await, or sync
waiting, complete, or failed
pending, fulfilled, or rejected
11 Which method is used to schedule a callback function to be executed when a Promise is successfully resolved?
.resolve()
.catch()
.then()
.finally()
12
What does the async keyword do when placed before a function declaration?
13 Which of the following is typically processed as a macrotask (also known as a task)?
await operation
setTimeout callback
.then() callback
14 When the current script finishes execution, which queue does the event loop process first?
15 Which ES6 keyword is used to declare a variable whose value is not expected to change?
var
static
let
const
16
What is the primary advantage of using template literals (e.g., `Hello, ${name}!`) in ES6?
17
What is a key difference between an arrow function (=>) and a regular function declaration (function() {})?
this context.
18 In ES6 Modules, which keyword is used to make a function or variable from one file available for use in another file?
import
require
export
module
19
How would you import a function named calculate that has been exported as the default from a file named math.js?
import calculate from './math.js';
import { calculate } from './math.js';
require(calculate) from './math.js';
import './math.js' as calculate;
20 A function that remembers the variables from the environment where it was created, even after that environment has gone, is known as a:
21
Consider the following JavaScript code snippet. What will be logged to the console when innerFunc() is executed?
javascript
let x = 10;
function outer() {
var x = 20;
function inner() {
console.log(x);
}
return inner;
}
const innerFunc = outer();
x = 30;
innerFunc();
22
What is the output of the following code, and why does let behave differently from var in this context?
javascript
for (let i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 10);
}
23
What will the following code, which demonstrates a simple counter factory, log to the console?
javascript
function createCounter() {
let count = 0;
return {
increment: function() { count++; },
getCount: function() { return count; }
};
}
const counter1 = createCounter();
const counter2 = createCounter();
counter1.increment();
counter1.increment();
counter2.increment();
console.log(counter1.getCount(), counter2.getCount());
24
What is the output of this classic closure-related code snippet involving a loop with var?
javascript
function createFunctions() {
var funcs = [];
for (var i = 0; i < 3; i++) {
funcs[i] = function() {
return i;
};
}
return funcs;
}
const myFuncs = createFunctions();
console.log(myFuncs[0](), myFuncs[1](), myFuncs[2]());
25
Given the following code, what will the console.log statement output?
javascript
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
return ${this.name} makes a sound.;
};
const dog = new Animal('Rex');
console.log(dog.hasOwnProperty('name'), dog.hasOwnProperty('speak'));
26
What is the output of this code, which modifies a constructor's prototype after an instance has been created?
javascript
function Wizard(name) {
this.name = name;
}
const merlin = new Wizard('Merlin');
Wizard.prototype.castSpell = function() {
return 'Expecto Patronum!';
};
console.log(merlin.castSpell());
27
Which statement accurately describes the relationships between an instance, its constructor, and the prototype in JavaScript?
javascript
function Vehicle() {}
const car = new Vehicle();
car.constructor is the same as Vehicle
Vehicle.prototype is the same as car
car.constructor is the same as Vehicle.prototype
car.__proto__ is the same as Vehicle
28
What is the order of output for the following code snippet involving the event loop?
javascript
console.log('A');
setTimeout(() => console.log('B'), 0);
console.log('C');
29 In a web browser, when does the browser typically get an opportunity to perform UI rendering updates (like repainting)?
requestAnimationFrame is called.
30
What are the last two values logged by this promise chain?
javascript
Promise.resolve(1)
.then(val => {
console.log(val); // Logs 1
return val + 1;
})
.then(val => {
console.log(val); // Logs 2
// No explicit return
})
.then(val => {
console.log(val); // What is logged here?
return val + 1;
})
.then(val => {
console.log(val); // And here?
});
31
What is the output of the following code which uses Promise.all with a rejecting promise?
javascript
const p1 = Promise.resolve('Success 1');
const p2 = new Promise((resolve, reject) => setTimeout(() => reject('Error 2'), 100));
const p3 = Promise.resolve('Success 3');
Promise.all([p1, p2, p3])
.then(values => console.log('Resolved:', values))
.catch(error => console.log('Rejected:', error));
32
What is the final, ordered output of executing this async function?
javascript
async function fetchData() {
try {
const response = await Promise.reject('API Down');
return response;
} catch (error) {
return Caught: ${error};
} finally {
console.log('Fetch attempt finished.');
}
}
fetchData().then(console.log);
Fetch attempt finished.
Caught: API Down
Fetch attempt finished.
33
What is the precise order of logs in the console for the following snippet?
javascript
console.log('Start');
setTimeout(() => {
console.log('Timeout');
}, 0);
Promise.resolve().then(() => {
console.log('Promise');
});
console.log('End');
34
Predict the output of the following code, which contains nested microtasks and macrotasks.
javascript
setTimeout(() => console.log('A'), 0);
Promise.resolve().then(() => {
console.log('B');
setTimeout(() => console.log('C'), 0);
});
Promise.resolve().then(() => {
console.log('D');
Promise.resolve().then(() => console.log('E'));
});
console.log('F');
35
What is the correct sequence of logs for this complex asynchronous code?
javascript
async function async1() {
console.log('A');
await async2();
console.log('B');
}
async function async2() {
console.log('C');
}
console.log('D');
setTimeout(() => console.log('E'), 0);
async1();
new Promise(resolve => {
console.log('F');
resolve();
}).then(() => console.log('G'));
console.log('H');
36
What is the output of calling applyConfig(settings) given the function and object below?
javascript
const settings = {
width: 800,
theme: 'dark'
};
function applyConfig({ width = 1024, height = 768, theme }) {
console.log(w: {height}, t: ${theme});
}
applyConfig(settings);
SyntaxError occurs.
37
What does the following function log to the console when called as shown?
javascript
function combine(first, ...args) {
const combinedArgs = [...args, first];
return combinedArgs;
}
const result = combine('a', 'b', 'c', 'd');
console.log(result);
TypeError is thrown.
38
Given these two ES module files, what is the expected output when main.js is executed?
utils.js
javascript
export const PI = 3.14;
export default function area(radius) {
return PI radius radius;
}
main.js
javascript
import calculateArea, { PI as piValue } from './utils.js';
console.log(calculateArea(10), piValue);
SyntaxError because you cannot mix default and named imports.
39
What will be logged to the console by main.js, and what concept does this demonstrate about ES modules?
counter.js
javascript
export let count = 0;
export function increment() {
count++;
}
main.js
javascript
import { count, increment } from './counter.js';
console.log(count); // First log
increment();
console.log(count); // Second log
TypeError because imported bindings are constants.
40
What is logged to the console in this example of the module pattern using an IIFE?
javascript
const myModule = (function() {
let privateVar = 'secret';
function setVar(newVal) {
privateVar = newVal;
}
return {
getVar: () => privateVar,
updateVar: (val) => setVar(val)
};
})();
const anotherRef = myModule;
anotherRef.updateVar('changed');
console.log(myModule.getVar());
TypeError is thrown.
41
Analyze the following code snippet. What will be the exact order of the numbers logged to the console?
javascript
console.log(1);
setTimeout(() => {
console.log(2);
Promise.resolve().then(() => {
console.log(3);
});
console.log(4);
}, 0);
new Promise((resolve) => {
console.log(5);
resolve();
}).then(() => {
console.log(6);
});
queueMicrotask(() => {
console.log(7);
});
console.log(8);
42
Consider the following prototype chain manipulation. What will be the output of console.log(b instanceof C)?
javascript
function A() {}
function B() {}
function C() {}
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
const b = new B();
// The twist
C.prototype = A.prototype;
console.log(b instanceof C);
true
TypeError
undefined
false
43
What is the final console output of this code, which uses closures and asynchronous operations?
javascript
const createAsyncLogger = () => {
let log = [];
return (msg) => {
log.push(msg);
return new Promise(resolve => setTimeout(() => resolve(log), 0));
}
};
const logger1 = createAsyncLogger();
const logger2 = createAsyncLogger();
logger1("A");
logger2("B").then(l => console.log(l));
logger1("C").then(l => console.log(l));
["A", "C"] followed by ["B"]
["B"] followed by ["C"]
["A"] followed by ["B"], then ["C"]
["B"] followed by ["A", "C"]
44
What is the final value of the result array after this generator function is executed and controlled?
javascript
function gen1() {
yield 2;
yield 3;
}
function gen2() {
yield 1;
yield* gen1();
yield 4;
}
const iterator = gen2();
const result = [];
for (const val of iterator) {
result.push(val);
if (val === 2) {
iterator.return('finished');
}
}
[1, 2, 'finished']
[1, 3, 4]
[1, 2, 3, 4]
[1, 2]
45
What will be logged to the console by the call to func()? Note the difference between direct and indirect eval.
javascript
var x = 'global';
function func() {
var x = 'local';
const indirectEval = eval;
indirectEval('console.log(x)');
}
func();
local
undefined
ReferenceError is thrown.
global
46
Given the async function main, which utilizes Promise.all with a mix of promises, what will be the output logged to the console?
javascript
function fetcher(val, delay, fail = false) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (fail) reject(val);
else resolve(val);
}, delay);
});
}
async function main() {
console.log('Start');
try {
const result = await Promise.all([
fetcher('A', 200),
fetcher('B', 100, true),
fetcher('C', 300)
]);
console.log(result);
} catch (error) {
console.log(Caught: ${error});
}
console.log('End');
}
main();
Start -> End -> Caught: B
Start -> Caught: B -> End
Start -> A Promise object -> End
Start -> ['A', 'B', 'C'] -> End
47
Module counter.js exports a variable. Module main.js imports it and attempts to reassign it. What is the result of running main.js?
counter.js
javascript
export let count = 0;
export function increment() {
count++;
}
main.js
javascript
import { count, increment } from './counter.js';
console.log(count); // First log
increment();
console.log(count); // Second log
try {
count = 10;
} catch (e) {
console.log(e.name);
}
0, 0, ReferenceError
0, 1, TypeError
0, 1, 10
48
Analyze the timing of operations in this code. Which of the following statements most accurately describes the output?
javascript
console.log('Start');
setTimeout(() => {
console.log('Timeout finished');
}, 20);
const promise = new Promise(resolve => {
// Simulate a long synchronous operation
const start = Date.now();
while (Date.now() - start < 100) {}
resolve('Promise finished');
});
promise.then(val => console.log(val));
console.log('End');
49
What is the precise order of console logs for the following snippet involving async/await, Promises, and setTimeout?
javascript
async function async1() {
console.log('A');
await async2();
console.log('B');
}
async function async2() {
console.log('C');
}
console.log('D');
setTimeout(() => console.log('E'), 0);
async1();
new Promise((resolve) => {
console.log('F');
resolve();
}).then(() => {
console.log('G');
});
console.log('H');
50
What is the stringified JSON output of the result object after performing this advanced destructuring assignment?
javascript
const data = {
id: 1,
user: {
name: 'John',
address: {
city: 'NY',
country: 'USA'
}
},
posts: [
{ title: 'Post 1', tags: ['a'] },
{ title: 'Post 2', tags: ['b'] }
]
};
const {
user: { name: userName, ...restOfUser },
posts: [firstPost, ],
id: userID = 10
} = data;
const result = { userName, restOfUser, firstPost, userID };
console.log(JSON.stringify(result));
{"userName":"John","restOfUser":{"address":{"city":"NY","country":"USA"}},"firstPost":{"title":"Post 1","tags":["a"]},"userID":1}
{"userName":"John","restOfUser":{"address":{"city":"NY","country":"USA"}},"firstPost":[{"title":"Post 1","tags":["a"]}],"userID":1}
{"userName":"John","restOfUser":{"address":{}},"firstPost":{"title":"Post 1","tags":["a"]},"userID":1}
{"userName":"John","restOfUser":{"city":"NY","country":"USA"},"firstPost":{"title":"Post 1"},"userID":10}
51
What is the console output of the raceTest function? Pay close attention to the contents of the array passed to Promise.race().
javascript
const p1 = new Promise((resolve) => setTimeout(() => resolve('P1 resolved'), 100));
const p2 = new Promise((_, reject) => setTimeout(() => reject('P2 rejected'), 50));
async function raceTest() {
try {
const result = await Promise.race([p1, p2, 'Instant Value']);
console.log(Result: ${result});
} catch (error) {
console.log(Error: ${error});
}
}
raceTest();
Error: P2 rejected
Result: P1 resolved
Result: Instant Value
52
What sequence of names will be logged to the console? Assume this code runs in a non-strict browser environment where this in the global scope refers to the window object.
javascript
this.name = 'Window';
const myObj = {
name: 'MyObj',
regularFunc: function() {
const arrowFunc = () => console.log(this.name);
arrowFunc();
},
arrowHost: function() {
const arrowFuncInArrow = () => console.log(this.name);
return { run: arrowFuncInArrow };
},
topLevelArrow: () => console.log(this.name)
};
myObj.regularFunc();
myObj.arrowHost().run();
myObj.topLevelArrow();
MyObj, MyObj, MyObj
MyObj, Window, Window
MyObj, MyObj, Window
Window, Window, Window
53
A web application creates a DOM element with an event listener. Profiling shows that a large data object is not garbage collected even after the element is removed from the DOM. Which code snippet demonstrates the most likely cause of this memory leak?
javascript
// A large dataset is fetched
const data = new Array(1e6).fill('some data');
function setupElement(id) {
const element = document.getElementById('my-element');
const specificValue = data[id];
// Which of these listener assignments causes the leak?
}
element.addEventListener('click', () => { console.log(specificValue); });
const val = data[id]; element.addEventListener('click', () => { console.log(val); });
element.addEventListener('click', function() { console.log(this.id); });
element.addEventListener('click', () => { console.log(data[id]); });
54
What is the final value of output3 after the prototype chain is dynamically rewired using Object.setPrototypeOf?
javascript
const dog = {
bark() { return 'Woof!'; }
};
const cat = {
purr() { return 'Purrr'; }
};
const animal = {
speak() {
if (this.bark) return this.bark();
if (this.purr) return this.purr();
}
};
Object.setPrototypeOf(dog, animal);
const myPet = Object.create(dog);
// Rewiring the chain
Object.setPrototypeOf(myPet, cat);
Object.setPrototypeOf(cat, animal);
const output3 = myPet.bark ? myPet.bark() : 'No bark';
Woof!
undefined
TypeError: myPet.bark is not a function
No bark
55
Consider these two ES modules. What is the final console output when main.js is executed? Pay close attention to module execution timing.
widget.js
javascript
console.log('Widget module executed');
export default () => 'I am a widget';
main.js
javascript
console.log('Main script start');
import('./widget.js').then(() => console.log('First import resolved'));
async function loadWidget() {
console.log('Inside loadWidget');
const { default: widget } = await import('./widget.js');
console.log(widget());
}
loadWidget();
console.log('Main script end');
Main script start, Inside loadWidget, Main script end, Widget module executed, First import resolved, I am a widget
Main script start, Main script end, Inside loadWidget, Widget module executed, I am a widget, First import resolved
Main script start, Inside loadWidget, Main script end, Widget module executed, I am a widget, First import resolved
Main script start, Main script end, Widget module executed, Inside loadWidget, First import resolved, I am a widget
56
This code uses a Proxy to validate property access and assignment. Assuming the code is executed in strict mode, what will be the final value of the output variable?
javascript
'use strict';
const target = {
id: '123',
value: 42
};
const handler = {
get(target, prop, receiver) {
if (prop.startsWith('')) {
console.log('Access to private property is denied');
return undefined;
}
return Reflect.get(...arguments);
},
set(target, prop, value, receiver) {
if (prop === 'value' && typeof value !== 'number') {
// Returning false from a 'set' trap in strict mode throws a TypeError
return false;
}
return Reflect.set(...arguments);
}
};
const proxy = new Proxy(target, handler);
let output;
try {
proxy.value = 'hello'; // This assignment will fail
output = proxy._id;
} catch (e) {
output = e.name;
}
undefined
Access to private property is denied
TypeError
42
57
What is the final console output of this promise chain, which includes recovery using .catch?
javascript
new Promise((resolve, reject) => {
console.log('A');
resolve(1);
reject('error'); // Ignored
})
.then(val => {
console.log('B');
throw new Error('C');
return val * 2; // Unreachable
})
.then(val => {
console.log('D');
})
.catch(err => {
console.log(err.message);
return 'E';
})
.then(val => {
console.log(val);
});
console.log('F');
A, F, B, C, E
F, A, B, C, E
A, B, C, D, E, F
A, F, B, D, E
58
What is the value of result? This question tests understanding of closures in a functional composition context.
javascript
const compose = (f, g) => (x) => f(g(x));
const add5 = (x) => x + 5;
const multiplyBy2 = (x) => x * 2;
const subtract10 = (x) => x - 10;
// Corresponds to subtract10(multiplyBy2(add5(x)))
const composedFunc = compose(subtract10, compose(multiplyBy2, add5));
const result = composedFunc(10);
20
15
-5
25
59
Which statement best explains why the delay for a setTimeout callback is not guaranteed?
javascript
const start = Date.now();
setTimeout(() => {
// The actual delay will be > 10ms
console.log(Fired after ${Date.now() - start}ms);
}, 10);
// Simulate a blocking operation
for (let i = 0; i < 2000000000; i++) {
// This loop takes > 10ms
}
setTimeout will never run.
setTimeout's delay is only a suggestion to the browser's rendering engine, which can choose to ignore it.
60
Given the following code, which statement is true regarding the relationship between F.prototype, obj1.__proto__, and obj2.constructor?
javascript
function F() {}
const obj1 = new F();
const obj2 = Object.create(F.prototype);
obj1.__proto__ is strictly equal to F.prototype, and obj2.constructor refers to the Object constructor.
obj1 and obj2 have a constructor property that points directly to F.
obj1.__proto__ is strictly equal to F.__proto__, and obj2.constructor is F.
obj1.prototype is strictly equal to F.prototype, and obj2.constructor is undefined.