Home >Web Front-end >JS Tutorial >5 More JavaScript Interview Exercises

5 More JavaScript Interview Exercises

Joseph Gordon-Levitt
Joseph Gordon-LevittOriginal
2025-02-20 08:59:08595browse

5 More JavaScript Interview Exercises

Following up on my previous article, "5 Typical JavaScript Interview Exercises," this piece explores additional common interview questions, focusing on key JavaScript concepts. Let's dive in!

Key Takeaways:

  • Closures are crucial: Understanding closures is essential. Remember, variable values within closures aren't fixed at the time of handler creation; they reflect the current value when the handler executes.
  • typeof operator quirks: typeof [] returns "object," not "Array." Use instanceof to reliably check for array types.
  • Event loop mechanics: The browser's event loop manages the event queue. setTimeout(), even with a zero delay, queues the callback for later execution.
  • isPrime() function optimization: Always validate inputs (negative numbers, 0, 1 aren't prime; 2 is the only even prime). Testing divisibility only up to the square root of the input significantly improves efficiency.

Question 1: Closures – The Classic Problem

Consider this code:

<code class="language-javascript">var nodes = document.getElementsByTagName('button');
for (var i = 0; i < nodes.length; i++) {
    nodes[i].addEventListener('click', function() {
        console.log('You clicked element #' + i);
    });
}</code>

What's the output when clicking the first and fourth buttons? Why?

Answer:

This highlights closure behavior. The code will print "You clicked element #[number of buttons]" twice. The i variable is shared across all event handlers. By the time any button is clicked, the loop has finished, and i holds its final value (the number of buttons).

Question 2: Fixing the Closure Issue

Modify the previous code to correctly print the button's index (0 for the first, 1 for the second, etc.).

Answer:

Two solutions:

Solution 1 (IIFE):

<code class="language-javascript">var nodes = document.getElementsByTagName('button');
for (var i = 0; i < nodes.length; i++) {
    nodes[i].addEventListener('click', (function(i) {
        return function() {
            console.log('You clicked element #' + i);
        };
    })(i));
}</code>

Solution 2 (Wrapper Function):

<code class="language-javascript">function handlerWrapper(i) {
    return function() {
        console.log('You clicked element #' + i);
    };
}

var nodes = document.getElementsByTagName('button');
for (var i = 0; i < nodes.length; i++) {
    nodes[i].addEventListener('click', handlerWrapper(i));
}</code>

Question 3: Data Type Gotchas

What's the output of this?

<code class="language-javascript">console.log(typeof null);
console.log(typeof {});
console.log(typeof []);
console.log(typeof undefined);</code>

Answer:

<code>object
object
object
undefined</code>

Note the surprising "object" for arrays. Use myArray instanceof Array for accurate array type checking.

Question 4: Event Loop Order

What's the output and why?

<code class="language-javascript">function printing() {
    console.log(1);
    setTimeout(function() { console.log(2); }, 1000);
    setTimeout(function() { console.log(3); }, 0);
    console.log(4);
}

printing();</code>

Answer:

<code>1
4
3
2</code>

The event loop explains this. setTimeout callbacks are queued, even with a 0ms delay. They execute after the main thread completes.

Question 5: The isPrime() Algorithm

Write a function isPrime(number) that returns true if the number is prime, false otherwise.

Answer:

<code class="language-javascript">var nodes = document.getElementsByTagName('button');
for (var i = 0; i < nodes.length; i++) {
    nodes[i].addEventListener('click', function() {
        console.log('You clicked element #' + i);
    });
}</code>

This optimized version handles input validation and only checks odd numbers up to the square root.

Conclusion:

These exercises cover fundamental JavaScript concepts frequently tested in interviews. Practice these to strengthen your understanding and improve your interview performance.

The above is the detailed content of 5 More JavaScript Interview Exercises. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn