This study guide covers possible questions for Quiz 3. I answered each question based on my understanding to help me prepare.
Sources:
Take Practice QuizQ1. How can you change the CSS class of an element using JavaScript?
Use element.classList.add('class'), element.classList.remove('class'), or element.classList.toggle('class') to modify CSS classes. This is preferred over directly manipulating inline styles because it maintains separation between JavaScript behavior and CSS presentation.
Q2. What does calling event.preventDefault() do in an event handler?
It stops the browser's default behavior for that event. For example, calling it on a form's submit event prevents the page from reloading, and calling it on a link's click event prevents navigation to the href URL. This lets you handle the event with custom JavaScript logic instead.
Q3. What does destructuring do in JavaScript?
Destructuring unpacks values from arrays or properties from objects into separate variables in a single statement. For arrays: const [x, y] = [1, 2]. For objects: const {name, age} = person. It can also be used in function parameters to extract specific properties from an argument object.
Q4. What does the Document Object Model (DOM) represent?
The DOM is a tree-like structure of element nodes that represents the HTML document. It's the browser's interpretation of the HTML, and JavaScript can access and manipulate this tree programmatically through the document object. The DOM IS the rendered HTML, not the source code.
Q5. What does the document.querySelector() method return when used in JavaScript?
It returns the first element that matches the specified CSS selector, or null if no match is found. It's the most flexible selection method because it accepts any valid CSS selector (ID, class, tag, descendant, etc.).
Q6. What is a callback function?
A callback function is a function passed as an argument to another function, which then "calls back" to execute it when needed. For example, in setTimeout(myFunction, 1000), myFunction is the callback that gets executed after 1 second. Don't use parentheses when passing—that would call it immediately.
Q7. What is a closure in JavaScript?
A closure occurs when a function "remembers" and can access variables from its surrounding scope, even after that outer scope has finished executing. This allows functions to preserve data without relying on global variables. The inner function "closes over" the variables it references.
Q8. What is an ARIA live region used for?
An ARIA live region (using aria-live="polite") notifies screen readers when content changes dynamically on the page. When content inside the live region updates, the screen reader announces the change to the user. Always use "polite" to avoid interrupting current content.
Q9. What is the difference between named and default exports in ES6 modules?
Named exports: Use export const foo = ... and import with braces: import {foo} from './module.js'. You can have multiple named exports per file.
Default exports: Use export default value and import without braces: import anyName from './module.js'. Only one default export per file. Named exports are generally preferred.
Q10. What is the main difference between a named function and an anonymous function assigned to a variable?
The main difference is hoisting. Named function declarations (function foo() {}) are hoisted to the top of their scope, so they can be called before they appear in the code. Anonymous functions assigned to variables (const foo = function() {}) are not hoisted, so they must be defined before use. Best practice: declare all functions before using them.
Q11. What is the main purpose of ES6 (ECMAScript 2015) in JavaScript development?
ES6 introduced "syntactic shortcuts" and new features that make JavaScript more concise, readable, and expressive. Key additions include arrow functions, destructuring, spread operator, let/const, template literals, classes, and modules. It was a major revision that modernized the language.
Q12. What is the output of the following code?const arr = ['a', 'b', 'c']; arr[5] = 'f'; console.log(arr.length);
The output is 6. When you assign a value to an index beyond the array's current length, JavaScript automatically extends the array. The indices 3 and 4 become "empty slots" (undefined), and the length becomes 6 to accommodate index 5.
Q13. What is the primary reason JavaScript is used in web development?
JavaScript enables interactivity and dynamic behavior in web pages. It's the only programming language that runs natively in web browsers, allowing developers to respond to user actions, manipulate the DOM, fetch data from servers, and create rich user experiences without page reloads.
Q14. What is the purpose of declaring 'use strict'; at the beginning of a JavaScript file?
It enables strict mode, which catches common coding errors that would otherwise fail silently. For example, assigning to an undeclared variable throws an error in strict mode instead of creating a global variable. It helps prevent bugs and enforces better coding practices.
Q15. What is the purpose of event.target in an event listener?
event.target refers to the specific element that triggered the event (the element that was actually clicked, for example). This is useful when you have event listeners on parent elements but need to know which child element was interacted with. It's the "target" of the user's action.
Q16. What is the purpose of the import statement in ES6 modules?
The import statement loads exported values from other JavaScript modules into the current file. It allows code organization by splitting functionality across multiple files. Syntax: import {foo, bar} from './module.js'. Local files need ./ prefix; library imports don't.
Q17. What is the spread operator (...) used for in JavaScript?
The spread operator ... expands array or object contents into a new context. Common uses include: copying arrays ([...arr]), copying objects ({...obj}), merging arrays ([...arr1, ...arr2]), and passing array elements as function arguments. It creates shallow copies.
Q18. Which array method is best used to perform an action on each element without returning a new array?
forEach() executes a callback function on each array element but does not return anything (returns undefined). Use it when you want to "do something" with each element (like logging or updating external state) rather than transforming the array.
Q19. Which array method is best used when you want to create a new array that contains only a subset of elements?
filter() creates a new array containing only elements for which the callback returns true. It acts as a "whitelist" mechanism. For example: numbers.filter(n => n > 5) keeps only numbers greater than 5.
Q20. Which is the more appropriate use case for passing a function as an argument?
Passing a function as an argument is appropriate when you want to specify what action should happen at a particular moment, especially for: event handlers (what to do when clicked), array methods (how to transform/filter each element), timers (what to do after delay), and async operations (what to do when data arrives).
Q21. Which keyword is used to make a variable in a module publicly accessible in ES6?
The export keyword makes variables, functions, or classes publicly accessible to other modules. Use export const foo = ... for named exports or export default for the default export. Without export, declarations are private to the module.
Q22. Which of the following array methods is used to transform each element of an array into a new array?
map() transforms each element using a callback function and returns a new array with the transformed values. The new array has the same length as the original. Example: nums.map(n => n * 2) doubles each number.
Q23. Which of the following best describes JavaScript as a programming language?
JavaScript is a dynamically-typed, interpreted language. Variables adopt the type of their current value (no type declarations needed), and type is determined at runtime. It supports multiple paradigms including object-oriented and functional programming.
Q24. Which of the following is NOT a benefit of using pure functions in JavaScript?
Pure functions are easier to test, reason about, and debug because they always produce the same output for the same input and have no side effects. However, pure functions are NOT beneficial when you need to modify external state, interact with the DOM, or perform I/O operations—those require impure functions.
Q25. Which of the following is NOT a characteristic of a pure function in JavaScript?
Pure functions: (1) operate only on their inputs, (2) never modify inputs—return new data instead, (3) produce no side effects, (4) always return identical outputs for identical inputs. A function that modifies global variables, changes its arguments, or logs to console is NOT pure.
Q26. Which of the following is NOT a reason you use block-body arrow functions instead of concise-body arrow functions?
Block-body arrow functions (() => { return ... }) are preferred for: readability, debugging (you can add breakpoints), and multi-statement logic. Concise-body (() => value) is shorter but sacrifices these benefits. Being "shorter" is NOT a reason to choose block-body—that's actually when you'd use concise-body.
Q27. Which of the following is true about the difference between an element's textContent and its innerHTML?
textContent treats content as plain text—HTML tags are escaped and displayed literally. innerHTML parses the string as HTML, so tags like <em> render as styled elements. Use textContent for plain text (safer), innerHTML for inserting HTML (but beware of security risks with untrusted content).
Q28. Which of the following statements about const is true?
const declares a variable whose reference cannot be reassigned. However, if the value is an object or array, you CAN still modify its properties or elements—const only prevents reassigning the variable itself. For truly immutable data, you'd need additional techniques like Object.freeze().
Q29. Which of the following statements about when to use arrow functions vs. function declarations is accurate?
Arrow functions should be the default choice for callbacks because they retain the lexical this context, preventing common bugs. Function declarations are better for top-level named functions, methods that need their own this, or when you need hoisting. Use arrow functions for short callbacks passed to array methods or event handlers.
Q30. Which of the following statements is NOT true about Object properties in JavaScript?
Object properties can be accessed with dot notation (obj.key) or bracket notation (obj['key']). Bracket notation is required when the key is stored in a variable or contains special characters. Properties can be added, modified, or deleted at any time. It is NOT true that object properties must be declared in advance.
Q31. Which of the following values is considered "falsy" in JavaScript?
Falsy values are: false, 0, '' (empty string), null, undefined, and NaN. All other values are truthy, including empty arrays [] and empty objects {}. This is important for conditional checks like if(value).
Q32. Why are arrow functions preferred for callbacks in JavaScript?
Arrow functions retain the lexical this from their surrounding scope, preventing the common bug where this changes unexpectedly inside callbacks. They also have shorter syntax, making code more concise. For callbacks in array methods and event handlers, arrow functions are the standard choice.
Q33. Why is it recommended to use === instead of == in JavaScript?
=== (strict equality) compares both value AND type without type coercion. == (loose equality) performs type coercion, leading to unexpected results like '40' == 40 being true. Using === prevents subtle bugs and makes comparisons predictable.
Q34. Why must a callback function passed to .map() return a value?
The map() method creates a new array by collecting the return value of the callback for each element. If the callback doesn't return anything, undefined will be placed in the new array for that element. The whole point of map is to transform values, so the callback must return the transformed value.