Notice: Due to an ongoing migration of our storage and publishing system, material requested since last month will not be uploaded for the time being, and new requests are paused. All existing notes remain available.
Question 1 of 59 · JavaScript syntax and data types · Easy
How do you write a single-line comment in JavaScript?
Not quite. Try another option.
Answer: // This is a comment
In JavaScript, single-line comments start with //. Multi-line comments are enclosed in /* ... */. <!-- ... --> is for HTML, and # is for languages like Python.
Question 2 of 59 · JavaScript syntax and data types · Easy
Which of the following is NOT a primitive data type in JavaScript?
Not quite. Try another option.
Answer: Object
JavaScript has several primitive data types like String, Number, Boolean, null, undefined, and Symbol. Object is a complex data type, not a primitive one.
Question 3 of 59 · Variables and scope · Easy
Which keyword is used to declare a variable that cannot be reassigned?
Not quite. Try another option.
Answer: const
The const keyword is used to declare a constant variable, which means its value cannot be reassigned after it's initialized. let and var declare variables that can be reassigned.
Question 4 of 59 · Variables and scope · Easy
What is the scope of a variable declared with the let keyword inside a code block {}?
Not quite. Try another option.
Answer: Block scope
Variables declared with let (and const) are block-scoped, meaning they are only accessible within the curly braces {} of the block where they are defined.
Question 5 of 59 · Operators and expressions · Easy
What is the result of the expression 5 + '5' in JavaScript?
Not quite. Try another option.
Answer: '55'
When the + operator is used with a number and a string, JavaScript performs type coercion and concatenates them, resulting in the string '55'.
Question 6 of 59 · Operators and expressions · Easy
Which operator is used for strict equality (checks both value and type)?
Not quite. Try another option.
Answer: ===
The strict equality operator === returns true only if the operands are of the same type and have the same value. The loose equality operator == performs type coercion before comparison.
Question 7 of 59 · Control flow statements · Easy
Which statement is used to execute a block of code only if a specified condition is true?
Not quite. Try another option.
Answer: if
The if statement is the fundamental control flow statement that allows JavaScript to make decisions and execute code conditionally.
Question 8 of 59 · Functions and arrow functions · Easy
Which syntax is correct for declaring a basic named function in JavaScript?
Not quite. Try another option.
Answer: function myFunction() {}
The standard way to declare a named function is by using the function keyword, followed by the function name, parentheses (), and a code block {}.
Question 9 of 59 · Arrays and objects · Easy
How do you access the first element of an array named fruits?
Not quite. Try another option.
Answer: fruits[0]
JavaScript arrays are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on. Elements are accessed using bracket notation [].
Question 10 of 59 · Arrays and objects · Easy
Which of the following correctly defines an empty object literal?
Not quite. Try another option.
Answer: {}
An empty object is created using curly braces {}. Square brackets [] create an empty array.
Question 11 of 59 · Basic event handling · Easy
Which JavaScript event is triggered when a user clicks an HTML element?
Not quite. Try another option.
Answer: onclick
The onclick event is fired when a pointing device button (like a mouse's primary button) is pressed and released on a single element.
Question 12 of 59 · Introduction to browser interaction · Easy
Which browser-specific function is used to display a simple message in a popup dialog box?
Not quite. Try another option.
Answer: alert()
The window.alert() method displays an alert dialog with an optional specified message and an OK button. It's commonly used for simple notifications to the user.
Question 13 of 59 · JavaScript syntax and data types · Easy
What will typeof true return?
Not quite. Try another option.
Answer: "boolean"
The typeof operator returns a string indicating the type of the unevaluated operand. true and false are boolean values, so typeof true returns the string "boolean".
Question 14 of 59 · Variables and scope · Easy
Before ES6 (2015), which was the only keyword available for declaring variables in JavaScript?
Not quite. Try another option.
Answer: var
var was the original keyword for variable declaration. It has function scope, unlike let and const which have block scope and were introduced in ES6.
Question 15 of 59 · Operators and expressions · Easy
What does the modulus operator (%) do?
Not quite. Try another option.
Answer: It returns the remainder of a division.
The modulus operator (%) is an arithmetic operator that returns the remainder when one operand is divided by another. For example, 10 % 3 evaluates to 1.
Question 16 of 59 · Control flow statements · Easy
Which keyword is used to stop the execution of a loop or a switch statement?
Not quite. Try another option.
Answer: break
The break statement terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
Question 17 of 59 · Functions and arrow functions · Easy
What is the correct syntax for a simple arrow function that takes no arguments?
Not quite. Try another option.
Answer: () => console.log('Hello');
Arrow function syntax provides a shorter way to write functions. For a function with no arguments, you use empty parentheses () followed by the fat arrow => and the function body.
Question 18 of 59 · Arrays and objects · Easy
Which array method adds one or more elements to the end of an array and returns the new length?
Not quite. Try another option.
Answer: push()
The push() method is used to add new items to the end of an array. pop() removes from the end, and shift() removes from the beginning.
Question 19 of 59 · Control flow statements · Easy
How do you correctly start a for loop that counts from 0 to 4?
Not quite. Try another option.
Answer: for (let i = 0; i < 5; i++)
A for loop in JavaScript has three parts inside the parentheses, separated by semicolons: initialization (let i = 0), condition (i < 5), and final-expression (i++).
Question 20 of 59 · Basic event handling · Easy
What is the modern, recommended way to attach an event handler to an HTML element using JavaScript?
addEventListener() is the standard and most flexible way to handle events. It allows you to add multiple event listeners for the same event to one element without overwriting existing event handlers.
Question 21 of 59 · Operators and expressions · Medium
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);
Not quite. Try another option.
Answer: "53" and 2
The + operator performs string concatenation when one of the operands is a string, resulting in '5' + 3 becoming '53'. However, the - operator is exclusively a numeric operator, so it coerces the string '5' into the number 5 before performing subtraction, resulting in 5 - 3 which is 2.
Question 22 of 59 · Variables and scope · Medium
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);
}
Not quite. Try another option.
Answer: 3, 3, 3
Because var is function-scoped (or globally-scoped here), there is only one i variable shared by all loop iterations. The setTimeout callbacks are executed after the loop has finished. By that time, the value of i has become 3. Therefore, all three callbacks log the final value of i, which is 3.
Question 23 of 59 · Functions and arrow functions · Medium
Consider the following object. What will person.greet() log to the console?
Arrow functions do not have their own this binding. Instead, they inherit this from the surrounding (lexical) scope. In this case, the arrow function is defined in the global scope where this refers to the global object (window in browsers), which does not have a name property. Thus, this.name is undefined.
Question 24 of 59 · Arrays and objects · Medium
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);
Not quite. Try another option.
Answer: The original array is mutated by splice but not by slice.
The slice() method returns a shallow copy of a portion of an array into a new array object without modifying the original array. The splice() method, however, changes the contents of an array by removing or replacing existing elements and/or adding new elements in place, thus mutating the original array.
Question 25 of 59 · Control flow statements · Medium
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++;
}
Not quite. Try another option.
Answer: 2
The continue statement terminates the execution of the statements in the current iteration of the loop and continues execution of the loop with the next iteration. The condition i % 2 === 0 is true for i = 0, 2, 4. In these cases, count++ is skipped. The count is only incremented when i is 1 and 3. Therefore, the final value of count is 2.
Question 26 of 59 · Operators and expressions · Medium
What will the values of resultA and resultB be?
JavaScript
const value = 0;
const resultA = value || 'default';
const resultB = value ?? 'default';
Not quite. Try another option.
Answer: resultA is 'default', resultB is 0
The Logical OR (||) operator returns the right-hand side operand if the left-hand side is any falsy value (e.g., 0, '', false, null, undefined). Since 0 is falsy, resultA becomes 'default'. The Nullish Coalescing (??) operator, however, only returns the right-hand side operand if the left-hand side is null or undefined. Since 0 is neither null nor undefined, resultB is assigned the value of 0.
Question 27 of 59 · Basic event handling · Medium
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?
Answer: Child's handler first, then Parent's handler (Bubbling)
The default event propagation model in modern browsers is event bubbling. This means the event is first triggered on the innermost target element (#child), and then it 'bubbles up' to its ancestors in the DOM tree. So, the child's click handler will execute first, followed by the parent's.
Question 28 of 59 · Introduction to browser interaction · Medium
Which code snippet correctly creates a new <p> element with the text "Hello World" and appends it to a div with the id container?
The correct DOM API methods are document.createElement() to create a new element node, setting its textContent property for the text, and then using appendChild() on the parent element to insert it into the DOM. While the innerHTML option also works, the question asks to create and append, which is best represented by the first option's programmatic approach.
Question 29 of 59 · Variables and scope · Medium
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);
Not quite. Try another option.
Answer: 20, then 10
This demonstrates variable shadowing and lexical scope. Inside the test function, a new block-scoped variable x is declared and initialized to 20. This shadows the outer x. The first console.log(x) refers to this inner x, so it logs 20. After the function call, the second console.log(x) is in the global scope and refers to the original x declared at the top, so it logs 10.
Question 30 of 59 · JavaScript syntax and data types · Medium
What is the result of typeof null in JavaScript?
Not quite. Try another option.
Answer: "object"
This is a well-known historical quirk in JavaScript. The typeof null operator returns "object". It's considered a bug that has not been fixed to avoid breaking existing code on the web. The correct way to check for null is by using the strict equality operator: myVar === null.
Question 31 of 59 · Arrays and objects · Medium
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;
Not quite. Try another option.
Answer: ['d']
Array destructuring allows you to unpack values from arrays. first is assigned 'a'. The comma , skips the second element ('b'). third is assigned 'c'. The rest operator ...rest collects all remaining elements into a new array. The only remaining element is 'd', so rest becomes ['d'].
Question 32 of 59 · Control flow statements · Medium
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);
Not quite. Try another option.
Answer: "Editor Admin "
The switch statement starts matching at case 2. Since there is no break statement in case 2, execution 'falls through' to case 3. The code in case 3 is executed, and then the break statement is encountered, which exits the switch block. Therefore, access is first concatenated with 'Editor ' and then with 'Admin '.
Question 33 of 59 · Functions and arrow functions · Medium
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;
}
Not quite. Try another option.
Answer: 15
The function uses a default parameter for y. When calculate is called with only one argument (5), x is set to 5. The default value for y is then calculated based on x, so y becomes 5 * 2 = 10. The function then returns x + y, which is 5 + 10 = 15.
Question 34 of 59 · Operators and expressions · Medium
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;
Not quite. Try another option.
Answer: x is 1, y is 10
The post-increment operator x++ first returns the current value of x (which is 0) for the expression evaluation, and then increments x. The || operator evaluates the left side. Since 0 is a falsy value, the operator proceeds to evaluate the right side, which is 10. Thus, y is assigned 10. Independently, x was incremented to 1 after its value was used in the expression.
Question 35 of 59 · Introduction to browser interaction · Medium
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;
Not quite. Try another option.
Answer: innerHTML parses the string as HTML, while textContent inserts it as raw text.
Setting innerHTML causes the browser to parse the assigned string as HTML and create the corresponding DOM nodes. div.innerHTML = '<strong>Hello</strong>' will result in bold text. Setting textContent treats the string as plain text; any HTML tags within it are rendered literally, not interpreted. div.textContent = '<strong>Hello</strong>' will display the literal string '<strong>Hello</strong>' on the page.
Question 36 of 59 · Basic event handling · Medium
What is the primary purpose of event.preventDefault() when used inside an event handler for a form's submit event?
Not quite. Try another option.
Answer: To stop the form from submitting and the page from reloading.
The default action of a form submission is to send the data to a server and reload the page. event.preventDefault() is used to cancel this default browser behavior. This is essential in modern single-page applications (SPAs) where form submissions are typically handled by JavaScript (e.g., using AJAX/Fetch) without a full page refresh.
Question 37 of 59 · Arrays and objects · Medium
What is the content of obj after this code is executed?
JavaScript
const propName = 'status';
const value = 'active';
const obj = {
id: 123,
[propName]: value
};
Not quite. Try another option.
Answer: { id: 123, status: 'active' }
This code uses a computed property name. The square brackets [] around propName in the object literal cause the expression inside them to be evaluated. The result of that evaluation (the string 'status') is then used as the property key. The value of that property is set to the value of the value variable ('active').
Question 38 of 59 · Variables and scope · Medium
What will be logged to the console?
JavaScript
console.log(message);
var message = 'Hello, Hoisting!';
Not quite. Try another option.
Answer: undefined
In JavaScript, declarations made with var are 'hoisted' to the top of their scope, but their initializations are not. The code is interpreted by the engine as if it were written like this:
JavaScript
var message; // Declaration is hoisted
console.log(message); // Logs undefined
message = 'Hello, Hoisting!'; // Initialization happens here
Therefore, when `console.log` is called, the `message` variable has been declared but not yet assigned a value, so its value is `undefined`.
Question 39 of 59 · JavaScript syntax and data types · Medium
Which of the following comparisons will result in true?
Not quite. Try another option.
Answer: null == undefined
The loose equality operator (==) performs type coercion. According to the specification, null is only loosely equal to undefined (and itself).
'2' === 2 is false because strict equality (===) checks for both value and type.
So, the correct answer is null == undefined.
Question 40 of 59 · Functions and arrow functions · Medium
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);
Not quite. Try another option.
Answer: 15
This is an IIFE. The function (function(a, b) { ... }) is declared and immediately called with the arguments (5, 10). Inside the function, a is 5 and b is 10. It calculates the sum (15) and returns it. This return value is assigned to the result constant. Finally, console.log(result) prints the value that was returned from the function, which is 15.
Question 41 of 59 · Variables and scope · Hard
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);
}
Not quite. Try another option.
Answer: 3, 3, 3, and then 0, 1, 2
This question tests the understanding of scope (var vs. let) and closures.
In the first loop, the variable i is declared with var, which has function scope (or global scope here). By the time the setTimeout callbacks execute, the loop has already completed, and the value of i is 3. Since all three callbacks share a closure over the same i variable, they all log 3.
In the second loop, the variable j is declared with let, which has block scope. A new lexical environment is created for each iteration of the loop. Each setTimeout callback captures a different j variable with the value from its specific iteration (0, 1, and 2). Therefore, it logs 0, 1, and 2.
Question 42 of 59 · Operators and expressions · Hard
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';
Not quite. Try another option.
Answer: A SyntaxError is thrown.
This question tests knowledge of operator precedence, specifically the interaction between the logical OR (||) and the nullish coalescing operator (??). The ECMAScript specification explicitly forbids combining || and && directly with ?? without parentheses to avoid ambiguity and potential bugs. Trying to evaluate y || x ?? 'default' will result in a SyntaxError: Unexpected token '??'. The expression must be clarified with parentheses, for example, (y || x) ?? 'default' or y || (x ?? 'default').
Question 43 of 59 · Arrays and objects · Hard
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);
Not quite. Try another option.
Answer: 5
Object.freeze() performs a shallow freeze. It makes the top-level properties of the config object immutable, but it does not recursively freeze nested objects. In this case, config.id cannot be changed, and because we are in 'use strict' mode, the attempt obj.id = 2; throws a TypeError, which is caught by the try...catch block. However, the config.settings object itself is not frozen. Therefore, the line obj.settings.retries = 5; successfully modifies the property of the nested object. The final console.log will output 5.
Question 44 of 59 · Functions and arrow functions · Hard
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();
Not quite. Try another option.
Answer: Alice
This question tests the lexical scoping of this in arrow functions. The greet function is an arrow function defined inside the User constructor. Arrow functions capture the this value of the enclosing execution context at the time they are created. In this case, greet captures the this from the User constructor, which refers to the newly created instance (user). The nestedGreet function, also an arrow function, is defined inside greet. It too captures its this from its enclosing context, which is greet. Since greet's this is the user instance, nestedGreet's this is also the user instance. Therefore, this.name correctly resolves to 'Alice'.
Question 45 of 59 · Control flow statements · Hard
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);
Not quite. Try another option.
Answer: o0i0i1i2o1i0o2i0i1i2
This question tests the use of labeled continue statements. The outer_loop label is applied to the outer for loop. When the condition i === 1 && j === 1 is met, the continue outer_loop; statement is executed. This statement does not just continue the inner loop; it stops the current iteration of the outer loop and begins its next iteration.
i=0: The inner loop completes fully. result becomes o0i0i1i2.
i=1: The outer loop adds o1. The inner loop runs for j=0, adding i0. result is now o0i0i1i2o1i0. When j=1, the continue outer_loop is triggered. The rest of the inner loop and the outer loop's current iteration are skipped.
i=2: The outer loop starts its next iteration. It adds o2 and the inner loop completes fully, adding i0i1i2. The final result is o0i0i1i2o1i0o2i0i1i2.
Question 46 of 59 · JavaScript syntax and data types · Hard
What are the values of res1 and res2 after this code executes?
This is a classic JavaScript type coercion puzzle.
For res2 = [] + {}, the + operator triggers string concatenation. [] is coerced to an empty string ''. {} is coerced to the string '[object Object]'. The result is '' + '[object Object]', which is '[object Object]'.
For res1 = {} + [], the JavaScript parser interprets the initial {} not as an object literal, but as an empty code block. Therefore, the expression is evaluated as {}; + []. The empty block does nothing. The expression then becomes + []. The unary + operator coerces its operand to a number. [] coerces to '', and +'' coerces to 0. So, res1 is 0.
Question 47 of 59 · Basic event handling · Hard
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?
Answer: div1 capture, p target, div2 bubble, div1 bubble
This question assesses understanding of the three phases of DOM event propagation: capture, target, and bubble.
Capture Phase: The event travels from the root down to the target element. Listeners registered with useCapture = true (the third argument to addEventListener) are fired. Here, div1's capture listener fires first. console.log('div1 capture').
Target Phase: The event reaches the target element (p). The listener on p is executed. console.log('p target').
Bubble Phase: The event travels back up from the target to the root. Listeners registered without useCapture = true (the default) are fired. It first hits div2's parent, which is div2. console.log('div2 bubble'). Then it bubbles up to div1. console.log('div1 bubble').
The final order is: div1 capture, p target, div2 bubble, div1 bubble.
Question 48 of 59 · Variables and scope · Hard
What is the output of this code?
JavaScript
function checkTDZ() {
console.log(a);
let a = 10;
}
try {
checkTDZ();
} catch (e) {
console.log(e.name);
}
Not quite. Try another option.
Answer: ReferenceError
This question tests the concept of the Temporal Dead Zone (TDZ). Variables declared with let and const are block-scoped and are not initialized until their definition is evaluated. The period from the start of the block until the declaration is encountered is the TDZ for that variable. Accessing the variable a within the TDZ, as done by console.log(a), results in a ReferenceError. This is different from var, which would be hoisted and initialized with undefined, logging undefined.
This question tests the specified behavior of Array.prototype.forEach when the array is modified during iteration. According to the ECMAScript specification:
The range of elements processed by forEach is set before the first invocation of the callback.
Elements that are appended to the array after the call to forEach begins will not be visited by the callback. (arr.push(4) adds an element that will not be visited).
If existing elements of the array are changed, their value passed to the callback will be the value at the time that element is visited. Elements that are deleted before being visited are not visited.
Execution trace:
Iteration 1 (index 0):num is 1. console.log(1) is executed. The if condition is true. arr.push(4) makes arr[1, 2, 3, 4]. arr.splice(1, 1) removes the element at index 1 (the 2), making arr[1, 3, 4]. The original 2 is now gone.
Iteration 2 (index 1):forEach now needs to visit the element at index 1 of the original array range. However, the current element at index 1 is now 3. So, num is 3. console.log(3) is executed.
Question 50 of 59 · Functions and arrow functions · Hard
This question tests a key difference between regular functions and arrow functions: the arguments object. Arrow functions do not have their own arguments object. Instead, they capture the arguments object from the closest non-arrow parent function. In this case, getArrow is an arrow function inside the regular function getData. Therefore, getArrow does not have its own arguments object; it uses the arguments object of getData. When myObject.getData('outer_arg1') is called, the arguments object for getData is ['outer_arg1']. So, arguments[0] inside getArrow refers to 'outer_arg1', not 'arg1'. The arguments passed to getArrow itself are ignored by the arguments object.
Question 51 of 59 · Introduction to browser interaction · Hard
Suppose you have the following code. In what order will the messages be logged to the console?
This question tests the understanding of the JavaScript Event Loop, specifically the difference between the macrotask (or task) queue and the microtask queue.
Synchronous code runs first: 'A: Script Start' and 'E: Script End' are logged immediately.
setTimeout places its callback in the macrotask queue.
Promise.resolve().then() places its callback in the microtask queue.
After the current script (the initial macrotask) is finished, the JavaScript engine checks the microtask queue. It must completely empty the microtask queue before starting a new macrotask.
The callback for 'C: Promise.then 1' is executed. This .then() returns a new promise which resolves, and its own .then() callback ('D: Promise.then 2') is added to the end of the microtask queue.
The engine checks the microtask queue again and finds the second promise callback. It is executed, logging 'D: Promise.then 2'.
The microtask queue is now empty. The engine can now process the next macrotask, which is the setTimeout callback. 'B: setTimeout' is logged.
The final order is A, E, C, D, B.
Question 52 of 59 · Operators and expressions · Hard
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++];
Not quite. Try another option.
Answer: 9
This tests a deep understanding of operator precedence and order of evaluation in JavaScript. The + operator has left-to-right associativity. The expression is evaluated as (arr[a] + (a += 1)) + arr[a++].
arr[a]: a is 1. arr[1] is 3. The expression is now (3 + (a += 1)) + arr[a++].
(a += 1): This is the pre-increment combined with assignment. a is incremented to 2, and the new value (2) is returned. The expression is now (3 + 2) + arr[a++].
3 + 2: This evaluates to 5. The expression is now 5 + arr[a++].
arr[a++]: This uses the post-increment operator. The current value of a (2) is used for the array index access first. arr[2] is 4. After this value is retrieved, a is incremented to 3. The expression is now 5 + 4.
5 + 4: This evaluates to 9.
So the final value of result is 9.
This question tests knowledge of Object.create(null) and its implications for an object's prototype chain.
Object.create(null) creates an object that does not have a prototype. It does not inherit from Object.prototype, which is where methods like hasOwnProperty, toString, etc., reside.
When obj.hasOwnProperty('prop') is called, JavaScript looks for the hasOwnProperty method on obj itself, and then on its prototype chain. Since obj has no prototype, the method is not found, resulting in a TypeError. The catch block catches this error and sets hasOwn to the error's name, which is 'TypeError'.
The in operator, however, works differently. It checks if a specified property is in an object or its prototype chain. Since prop is an own property of obj, 'prop' in obj evaluates to true.
The final output is TypeError, true.
Question 54 of 59 · JavaScript syntax and data types · Hard
What is the result of the expression 0.1 + 0.2 === 0.3 and why?
Not quite. Try another option.
Answer: false, because of floating-point inaccuracies inherent in the IEEE 754 standard.
This is a classic question about how numbers are represented in JavaScript. JavaScript uses the IEEE 754 standard for floating-point arithmetic. Binary representations of fractions like 0.1 and 0.2 are repeating and cannot be stored with perfect precision.
0.1 in binary floating point is something like 0.00011001100110011...
0.2 is something like 0.0011001100110011...
When these imprecise numbers are added, the result is very close to, but not exactly, 0.3. The actual result is 0.30000000000000004. Since 0.30000000000000004 is not strictly equal (===) to 0.3, the expression evaluates to false.
Question 55 of 59 · Control flow statements · Hard
The switch statement in JavaScript uses strict equality (===) for its comparisons.
Case 1: obj === { key: 'value' }. This comparison evaluates to false. Even though the two objects have the same structure and values, they are two different instances in memory. The strict equality operator checks for reference equality for objects, not structural equality.
Case 2: obj === obj. This comparison evaluates to true because it is comparing the object reference to itself.
Therefore, the code inside the second case is executed, and 'Case 2' is logged to the console.
Question 56 of 59 · Basic event handling · Hard
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();
}
});
Not quite. Try another option.
Answer: The browser may have already performed the default action (ticking the checkbox) before preventDefault() is called.
Event handlers in JavaScript run synchronously. When an async function is used as a handler, the browser invokes it, but it does not wait for the promise returned by the async function to resolve. The function executes up to the first await, then pauses, and control is returned to the event loop. The browser, having finished the synchronous part of the event handler, proceeds with the default action (e.g., ticking the checkbox). By the time the confirmAction() promise resolves and event.preventDefault() is called, it is too late to prevent the default action. To handle this correctly, one should call event.preventDefault()before the await and then manually re-trigger the action if the confirmation is successful.
Question 57 of 59 · Functions and arrow functions · Hard
What is the result of attempting to instantiate an arrow function with the new keyword?
Arrow functions are not constructible and do not have a [[Construct]] internal method. They also lack a prototype property. The new keyword is used to create an instance of an object from a constructor function. When you try to use new with an arrow function, JavaScript will throw a TypeError with a message like "ArrowConstructor is not a constructor". The try...catch block will catch this error, and the value of instance will become the name of the error, which is 'TypeError'.
This question tests the limitations and transformations that occur during the JSON.stringify and JSON.parse process, often used for deep cloning.
JSON.stringify has specific rules for converting values:
Functions (getSummary) are omitted.
undefined values (temp) are omitted.
Date objects are converted to their ISO 8601 string representation (e.g., "2023-10-27T10:00:00.000Z").
The resulting JSON string will not contain the getSummary or temp keys, and the lastLogin value will be a string. When JSON.parse reconstructs the object from this string, the lastLogin property will be a string, not a Date object. Therefore, typeof result.details.lastLogin will be 'string'.
Question 59 of 59 · Operators and expressions · Hard
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]);
Not quite. Try another option.
Answer: true, false, true, true
This question tests deep knowledge of the Abstract Equality Comparison Algorithm (==).
x == y ('10' == 10): When comparing a string and a number, the string is converted to a number. '10' becomes 10. 10 == 10 is true.
x === y ('10' === 10): Strict equality checks for both value and type. Since the types (string and number) are different, it's false.
y == [10] (10 == [10]): When comparing a primitive and an object, the object is converted to a primitive using ToPrimitive. For an array, this is equivalent to toString(). [10].toString() results in the string '10'. The comparison becomes 10 == '10', which, as in the first case, is true.
'1,0' == [1,0]: The array [1,0] is converted to a primitive via toString(), which calls join(','). [1,0].toString() results in the string '1,0'. The comparison becomes '1,0' == '1,0', which is true.
That's unit 2
Answer a few questions and your score shows up here.
Nearly through. Did unit 2 of INT219 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 2 of INT219 save you a night before the exam?
Then you can help keep it free for the next batch. Ads cover part of the server bill;
the rest comes out of a student's own pocket: the domain, the storage, and keeping
the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason.
to try again.