search
HomeWeb Front-endJS Tutorial3 JavaScript Interview Questions to Pay Attention to

JavaScript is the official language of all modern browsers. As a result, JavaScript questions are asked in developer interviews in various languages.

This article does not cover the latest JavaScript libraries, common development practices, or any new ES6 functions. Instead, let’s talk about 3 JavaScript questions that often come up in interviews. I asked these questions and my friends said they asked them too.

Of course this does not mean that you only need to learn these 3 questions when preparing for a JavaScript interview - you still have many ways to better prepare for the upcoming interview - but the interviewer is very likely to pass the following 3 questions To determine your understanding and mastery of JavaScript and DOM.

let's start! Note that we use native JavaScript in the examples below because interviewers usually want to test how well you understand JavaScript and the DOM without the help of a library (such as jQuery).

Question #1: Event Broker

When creating an application, sometimes you need to add event listeners to buttons, text, or pictures on the page, and trigger certain operations when the user interacts with these elements. .

Let’s take a simple to-do list as an example. The interviewer will tell you that they want to trigger an action when the user clicks on an item in the list. And let you use JavaScript to implement this function according to the following HTML code:

<ul id="todo-app">
  <li class="item">Walk the dog</li>
  <li class="item">Pay bills</li>
  <li class="item">Make dinner</li>
  <li class="item">Code for one hour</li>
</ul>

You may add event listeners to elements like the following code:

document.addEventListener(&#39;DOMContentLoaded&#39;, function() {

  let app = document.getElementById(&#39;todo-app&#39;);
  let items = app.getElementsByClassName(&#39;item&#39;);

  // 给每个列表项添加事件监听器
  for (let item of items) {
    item.addEventListener(&#39;click&#39;, function() {
      alert(&#39;you clicked on item: &#39; + item.innerHTML);
    });
  }

});

Of course the above code can complete the interview According to the official's needs, the problem is that each list item will be added with an event listener. This is fine when the list only has 4 items, but what if someone adds 10,000 items to their to-do list (maybe they have a lot to do)? At that point the function will create 10,000 event listeners and add them all to the DOM. This efficiency is very low. During the interview, it is best to first ask the interviewer how many to-do items a user can add at most. If there are never more than 10, then the above code will run without issue. But if there is no limit to the number of to-do items a user can enter, then you have to find a more efficient solution.

If the application has hundreds of event listeners, a more efficient solution is to add

an

event listener to the outermost container, and then get the actual event listener when the user actually clicks The clicked to-do item. This is called an event delegate and is more efficient than adding separate event listeners to each to-do item. Here is the code for the event proxy:

document.addEventListener(&#39;DOMContentLoaded&#39;, function() {

  let app = document.getElementById(&#39;todo-app&#39;);

  // 给容器添加事件监听器
  app.addEventListener(&#39;click&#39;, function(e) {
    if (e.target && e.target.nodeName === &#39;LI&#39;) {
      let item = e.target;
      alert(&#39;you clicked on item: &#39; + item.innerHTML);
    }
  });

});

Question #2: Using closures in loops

Closures are often asked in interviews because the interviewer can pass this Answers to the questions gauge your familiarity with the language and test whether you know when to use closures.

A closure is an

internal function

that can access variables outside the scope. Closures can be used to implement privatization and create factory functions. Common interview questions about closures are as follows: Write a function that loops over an

integer

array, and prints the index of each element in the array with a delay of 3 seconds. . The common (incorrect) implementation of this problem is as follows:

const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
  setTimeout(function() {
    console.log(&#39;The index of this number is: &#39; + i);
  }, 3000);
}

If you run this function, you will find that

4## is printed every time after 3 seconds. # instead of the expected

0, 1, 2, 3. In order to correctly find the reason for this situation, you need to understand how JavaScript runs this code, which is what the interviewer wants to examine you.

The reason is that the setTimeout function creates a function (closure) that accesses the outer scope, which is the loop containing index i. After 3 seconds, the function starts to print the value of i, and the loop ends at this time, and the value of i is already 4. Because after looping through 0, 1, 2, 3, 4, it finally stops at 4.

There are actually several ways to correctly solve this problem. Here are two:

const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
  // 给每个函数传入变量 i 让其能访问正确的索引
  setTimeout(function(i_local) {
    return function() {
      console.log(&#39;The index of this number is: &#39; + i_local);
    }
  }(i), 3000);
}
const arr = [10, 12, 15, 21];
for (let i = 0; i < arr.length; i++) {
  // 使用 ES6 中的 let 关键字,它会在函数调用时创建一个新的绑定
  // 了解更多:http://exploringjs.com/es6/ch_variables.html#sec_let-const-loop-heads
  setTimeout(function() {
    console.log(&#39;The index of this number is: &#39; + i);
  }, 3000);
}

Question #3: Debouncing

Some browser events can be triggered multiple times in a short period of time, such as window resizing or scrolling page. If you add an event listener to the window scroll event, and the user keeps scrolling down the page quickly, your event may be fired thousands of times in 3 seconds. This can cause very serious performance issues.

If the interview discusses building applications and scroll events, window resize events, or keyboard events, etc., be sure to mention debouncing or throttling as a way to improve page speed and performance. Let’s take an example of css-tricks:

In 2011, Twitter had a problem: when scrolling the Twitter summary, the page became very stuck or even unresponsive. John Resig wrote a blog about this issue, explaining how binding time-consuming functions directly to the scroll event is a bad idea.

Debouncing 是解决这个问题的一种方法,它的做法是限制下次函数调用之前必须等待的时间间隔。正确实现 debouncing 的方法是将若干个函数调用 合成 一次,并在给定时间过去之后仅被调用一次。下面是一个原生 JavaScript 的实现,用到了 作用域 , 闭包, this , 和 计时事件 :

// 将会包装事件的 debounce 函数
function debounce(fn, delay) {
  // 维护一个 timer
  let timer = null;
  // 能访问 timer 的闭包
  return function() {
    // 通过 ‘this’ 和 ‘arguments’ 获取函数的作用域和变量
    let context = this;
    let args = arguments;
    // 如果事件被调用,清除 timer 然后重新设置 timer
    clearTimeout(timer);
    timer = setTimeout(function() {
      fn.apply(context, args);
    }, delay);
  }
}

这个函数 — 当传入一个事件(fn)时 — 会在经过给定的时间(delay)后执行。

函数这样用:

// 当用户滚动时被调用的函数
function foo() {
  console.log(&#39;You are scrolling!&#39;);
}

// 在 debounce 中包装我们的函数,过 2 秒触发一次
let elem = document.getElementById(&#39;container&#39;);
elem.addEventListener(&#39;scroll&#39;, debounce(foo, 2000));

Throttling 是与 debouncing 类似的一种技术,但它不是在调用函数之前等待一段时间,throttling 是在较长的时间间隔内调用函数。所以如果一个事件每 100 毫秒被触发 10 次,throttling 会在每隔 2 秒时执行一次这个函数,而不是在 100 毫秒内执行 10 次事件。

 

The above is the detailed content of 3 JavaScript Interview Questions to Pay Attention to. 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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.