Unit 2 - Practice Quiz
1 How do you write a single-line comment in JavaScript?
/* This is a comment */
<!-- This is a comment -->
// This is a comment
# This is a comment
2 Which of the following is NOT a primitive data type in JavaScript?
3 Which keyword is used to declare a variable that cannot be reassigned?
const
static
var
let
4
What is the scope of a variable declared with the let keyword inside a code block {}?
5
What is the result of the expression 5 + '5' in JavaScript?
'55'
undefined
'5+5'
10
6 Which operator is used for strict equality (checks both value and type)?
===
!=
=
==
7 Which statement is used to execute a block of code only if a specified condition is true?
while
if
switch
for
8 Which syntax is correct for declaring a basic named function in JavaScript?
let myFunction = () => {}
def myFunction() {}
function myFunction() {}
myFunction = function() {}
9
How do you access the first element of an array named fruits?
fruits[0]
fruits.get(0)
fruits[1]
fruits.first()
10 Which of the following correctly defines an empty object literal?
()
[]
{}
new Object
11 Which JavaScript event is triggered when a user clicks an HTML element?
onmouseover
onclick
onchange
onsubmit
12 Which browser-specific function is used to display a simple message in a popup dialog box?
console.log()
prompt()
alert()
document.write()
13
What will typeof true return?
"boolean"
"undefined"
"string"
"number"
14 Before ES6 (2015), which was the only keyword available for declaring variables in JavaScript?
const
var
let
variable
15
What does the modulus operator (%) do?
16 Which keyword is used to stop the execution of a loop or a switch statement?
continue
exit
return
break
17 What is the correct syntax for a simple arrow function that takes no arguments?
function => console.log('Hello');
() -> console.log('Hello');
() => console.log('Hello');
=> () console.log('Hello');
18 Which array method adds one or more elements to the end of an array and returns the new length?
shift()
concat()
pop()
push()
19
How do you correctly start a for loop that counts from 0 to 4?
for (let i = 0 to 4)
loop (i = 0; i < 5; i++)
for (i = 0; i < 5)
for (let i = 0; i < 5; i++)
20 What is the modern, recommended way to attach an event handler to an HTML element using JavaScript?
element.addEventListener('click', myFunction);
element.onclick = myFunction;
element.attachEvent('onclick', myFunction);
<button onclick="myFunction()">
21
What will be logged to the console after running the following code snippet?
javascript
let a = '5';
let b = 3;
console.log(a + b);
console.log(a - b);
22
What is the output of the following code, which demonstrates a classic closure and scope issue with var?
javascript
for (var i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 10);
}
23
Consider the following object. What will person.greet() log to the console?
javascript
const person = {
name: 'Alice',
greet: () => {
console.log('Hello, ' + this.name);
}
};
person.greet();
24
What is the difference in the final state of the original array after running code A versus code B?
javascript
// Code A
const original = [1, 2, 3, 4, 5];
const newA = original.slice(1, 3);
// Code B
const original = [1, 2, 3, 4, 5];
const newB = original.splice(1, 3);
original array is mutated by splice but not by slice.
original array.
original array is mutated by slice but not by splice.
original array.
25
What will be the final value of count after this loop completes?
javascript
let count = 0;
for (let i = 0; i < 5; i++) {
if (i % 2 === 0) {
continue;
}
count++;
}
26
What will the values of resultA and resultB be?
javascript
const value = 0;
const resultA = value || 'default';
const resultB = value ?? 'default';
resultA is 0, resultB is 0
resultA is 0, resultB is 'default'
resultA is 'default', resultB is 0
resultA is 'default', resultB is 'default'
27
Imagine a <div> containing a <button>. Both have click event listeners attached. If a user clicks the button, in what order do the event handlers typically fire by default?
html
<div id="parent">
<button id="child">Click Me</button>
</div>
<script>
document.getElementById('parent').addEventListener('click', () => console.log('Parent clicked'));
document.getElementById('child').addEventListener('click', () => console.log('Child clicked'));
</script>
28
Which code snippet correctly creates a new <p> element with the text "Hello World" and appends it to a div with the id container?
html
<div id="container"></div>
const p = new Paragraph('Hello World');
document.getElementById('container').add(p);
const container = document.getElementById('container');
const p = document.create('p');
p.text = 'Hello World';
container.append(p);
const container = document.getElementById('container');
const p = document.createElement('p');
p.textContent = 'Hello World';
container.appendChild(p);
const container = document.querySelector('#container');
container.innerHTML = '<p>Hello World</p>';
29
What does the following code log to the console?
javascript
let x = 10;
function test() {
let x = 20;
console.log(x);
}
test();
console.log(x);
30
What is the result of typeof null in JavaScript?
31
Given the array const letters = ['a', 'b', 'c', 'd'];, what will be the value of the rest variable after this destructuring assignment?
javascript
const [first, , third, ...rest] = letters;
32
What is the output of this switch statement due to fall-through?
javascript
let level = 2;
let access = '';
switch (level) {
case 1:
access += 'User ';
case 2:
access += 'Editor ';
case 3:
access += 'Admin ';
break;
case 4:
access += 'SuperAdmin ';
}
console.log(access);
33
What is logged to the console when the following function is called as calculate(5)?
javascript
const calculate = (x, y = x * 2) => {
return x + y;
}
34
What are the final values of x and y after this code runs, considering short-circuiting and the post-increment operator?
javascript
let x = 0;
let y = x++ || 10;
x is 0, y is 10
x is 1, y is 1
x is 1, y is 0
x is 1, y is 10
35
What is the key difference between setting element.innerHTML and element.textContent?
javascript
const div = document.getElementById('myDiv');
const myString = '<strong>Hello</strong>';
// What happens differently here?
div.innerHTML = myString;
div.textContent = myString;
textContent parses the string as HTML, while innerHTML inserts it as raw text.
innerHTML parses the string as HTML, while textContent inserts it as raw text.
innerHTML is faster but less secure; textContent is slower but more secure.
36
What is the primary purpose of event.preventDefault() when used inside an event handler for a form's submit event?
37
What is the content of obj after this code is executed?
javascript
const propName = 'status';
const value = 'active';
const obj = {
id: 123,
[propName]: value
};
38
What will be logged to the console?
javascript
console.log(message);
var message = 'Hello, Hoisting!';
39
Which of the following comparisons will result in true?
false == 'false'
null == undefined
[] == ![]
'2' === 2
40
What is the output of the following Immediately Invoked Function Expression (IIFE)?
javascript
const result = (function(a, b) {
let sum = a + b;
return sum;
})(5, 10);
console.log(result);
sum is not defined globally
41
Consider the following JavaScript code snippet. What will be logged to the console?
javascript
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 10);
}
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log(j), 10);
}
42
What is the result of the following expression in a modern JavaScript engine?
javascript
let x = 0;
let y = null;
const result = y || x ?? 'default';
SyntaxError is thrown.
0
'default'
null
43
Given the following code, what is the output of console.log(config.settings.retries) after the attemptChange function is called?
javascript
'use strict';
const config = {
id: 1,
settings: {
retries: 3,
timeout: 5000
}
};
Object.freeze(config);
function attemptChange(obj) {
try {
obj.id = 2; // This will fail silently in non-strict mode, but throw in strict mode
obj.settings.retries = 5; // This modification is on a nested object
} catch (e) {
console.log('Error caught');
}
}
attemptChange(config);
console.log(config.settings.retries);
3
console.log(config.settings.retries) is never reached due to an unhandled error.
undefined
5
44
What is logged to the console when user.greet() is executed?
javascript
function User(name) {
this.name = name;
this.greet = () => {
const nestedGreet = () => {
console.log(this.name);
};
nestedGreet();
};
}
const user = new User('Alice');
user.greet();
undefined
TypeError is thrown because this is undefined.
Alice
45
What will be the output of the following code?
javascript
let result = '';
outer_loop:
for (let i = 0; i < 3; i++) {
result += o${i};
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
continue outer_loop;
}
result += i${j};
}
}
console.log(result);
o0i0i1i2o1i0o2i0i1i2
o0i0i1i2o1i0i1i2o2i0i1i2
o0i0i1i2o1i0o1i2o2i0i1i2
o0i0i1i2o1o2i0i1i2
46
What are the values of res1 and res2 after this code executes?
javascript
const res1 = {} + [];
const res2 = [] + {};
console.log(res1: {res2});
[object Object], res2: [object Object]
NaN, res2: [object Object]
0, res2: [object Object]
[object Object], res2: 0
47
Consider the following HTML and JavaScript. If a user clicks on the p element, in what order will the messages be logged to the console?
html
<div id="div1">
<div id="div2">
<p id="p_element">Click me</p>
</div>
</div>
javascript
const div1 = document.getElementById('div1');
const div2 = document.getElementById('div2');
const p = document.getElementById('p_element');
div1.addEventListener('click', () => console.log('div1 capture'), true);
div1.addEventListener('click', () => console.log('div1 bubble'));
div2.addEventListener('click', () => console.log('div2 bubble'));
p.addEventListener('click', () => console.log('p target'));
p target, div2 bubble, div1 bubble, div1 capture
div1 bubble, div2 bubble, p target, div1 capture
div1 capture, p target, div2 bubble, div1 bubble
div1 capture, div2 bubble, p target, div1 bubble
48
What is the output of this code?
javascript
function checkTDZ() {
console.log(a);
let a = 10;
}
try {
checkTDZ();
} catch (e) {
console.log(e.name);
}
TypeError
undefined
10
ReferenceError
49
What does the following code log to the console?
javascript
const arr = [1, 2, 3];
arr.forEach((num, index) => {
console.log(num);
if (index === 0) {
arr.push(4);
arr.splice(1, 1);
}
});
1, 2, 3, 4
1, 3, 4
1, 2, 3
1, 3
50
What is the result of the following code snippet?
javascript
const myObject = {
data: 'some data',
getData: function() {
const getArrow = () => arguments[0];
return getArrow('arg1', 'arg2');
}
};
console.log(myObject.getData('outer_arg1'));
ReferenceError because arguments is not defined in an arrow function.
arg1
outer_arg1
undefined
51
Suppose you have the following code. In what order will the messages be logged to the console?
javascript
console.log('A: Script Start');
setTimeout(() => {
console.log('B: setTimeout');
}, 0);
Promise.resolve().then(() => {
console.log('C: Promise.then 1');
}).then(() => {
console.log('D: Promise.then 2');
});
console.log('E: Script End');
A, C, D, E, B
A, E, B, C, D
A, E, C, D, B
A, B, C, D, E
52
What is the value of result in the following code?
javascript
let a = 1;
const arr = [2, 3, 4];
const result = arr[a] + (a += 1) + arr[a++];
11
9
10
53
What is the output of this code?
javascript
const obj = Object.create(null);
obj.prop = 'exists';
let hasOwn = false;
try {
hasOwn = obj.hasOwnProperty('prop');
} catch(e) {
hasOwn = e.name;
}
const hasIn = 'prop' in obj;
console.log({hasIn});
false, false
false, true
true, true
TypeError, true
54
What is the result of the expression 0.1 + 0.2 === 0.3 and why?
false, because of JavaScript's implicit type coercion to strings.
false, because of floating-point inaccuracies inherent in the IEEE 754 standard.
true, because the mathematical addition is correct.
true, because modern JavaScript engines have fixed this historical bug.
55
What will be logged to the console?
javascript
const obj = { key: 'value' };
switch (obj) {
case { key: 'value' }:
console.log('Case 1');
break;
case obj:
console.log('Case 2');
break;
default:
console.log('Default');
}
Case 1
Case 2
SyntaxError will be thrown.
Default
56
You have an async function as an event listener for a checkbox. What is a potential issue with the event.preventDefault() call in this code?
javascript
checkbox.addEventListener('click', async (event) => {
const userIsSure = await confirmAction(); // An async function that shows a dialog
if (!userIsSure) {
event.preventDefault();
}
});
preventDefault() is called.
event object is garbage collected after the await and cannot be accessed.
event.preventDefault() will throw an error because events cannot be handled asynchronously.
57
What is the result of attempting to instantiate an arrow function with the new keyword?
javascript
const ArrowConstructor = () => {
this.value = 42;
};
let instance;
try {
instance = new ArrowConstructor();
} catch (e) {
instance = e.name;
}
console.log(instance);
{ value: 42 }
TypeError
ReferenceError
undefined
58
What will be logged by console.log(result)?
javascript
const data = {
id: 1,
user: 'admin',
details: {
lastLogin: new Date(),
roles: ['read', 'write']
},
getSummary: function() { return ${this.user}; },
temp: undefined
};
const result = JSON.parse(JSON.stringify(data));
console.log(typeof result.details.lastLogin);
object
function
string
undefined
59
What is the output of the following code snippet?
javascript
let x = '10';
let y = 10;
console.log(x == y);
console.log(x === y);
console.log(y == [10]);
console.log('1,0' == [1,0]);
true, false, false, true
true, true, true, true
true, false, true, false
true, false, true, true