Web Development JavaScript 2 — Questions and Answers
Question 1: What does the `typeof` operator return for `null`?
- 'null'
- 'undefined'
- 'object' (Correct answer)
- 'boolean'
Correct answer: 'object'
`typeof null` returns `'object'` due to a long-standing bug in JavaScript that was never fixed for backwards compatibility.
Question 2: Which method removes the last element from an array and returns it?
- shift()
- pop() (Correct answer)
- splice()
- slice()
Correct answer: pop()
`Array.prototype.pop()` removes and returns the last element, mutating the original array.
Question 3: What is the output of `console.log(0.1 + 0.2 === 0.3)` in JavaScript?
- true
- false (Correct answer)
- NaN
- undefined
Correct answer: false
Floating-point arithmetic in JavaScript produces `0.30000000000000004`, so the strict equality check returns `false`.
Question 4: What does the `Array.from()` method do?
- Creates a shallow copy of an existing array
- Creates a new Array instance from an array-like or iterable object (Correct answer)
- Merges two arrays into one
- Converts an array to a string
Correct answer: Creates a new Array instance from an array-like or iterable object
`Array.from()` creates a new array from array-like objects (e.g., NodeLists, strings) or iterables.
Question 5: What is a closure in JavaScript?
- A function that calls itself
- A way to close browser windows via JS
- A function that retains access to its lexical scope even after the outer function has returned (Correct answer)
- A method to terminate a loop early
Correct answer: A function that retains access to its lexical scope even after the outer function has returned
A closure is created when an inner function captures and remembers variables from its surrounding scope.
Question 6: Which statement correctly declares a block-scoped variable in modern JavaScript?
- var x = 5;
- let x = 5; (Correct answer)
- int x = 5;
- variable x = 5;
Correct answer: let x = 5;
`let` declares a block-scoped variable, unlike `var` which is function-scoped.
Question 7: What does `JSON.stringify()` do when it encounters a function value in an object?
- Converts it to a string representation of the function
- Throws a TypeError
- Omits the key entirely (Correct answer)
- Converts it to null
Correct answer: Omits the key entirely
`JSON.stringify()` silently omits object properties whose values are functions because JSON has no function type.
What does the `typeof` operator return for `null`?