JavaScript is the official language of all modern browsers. As a result, JavaScript problems are encountered in all language developers ' interviews.
This article does not talk about the latest JavaScript libraries, general development practices, or any new ES6 functions. Instead, talk about the 3 JavaScript problems that often occur during an interview. I asked these questions, and my friends said they asked.
Not that you're just going to have to learn these 3 questions when you're preparing for a JavaScript interview-there are plenty of ways to better prepare for the upcoming interview-but the interviewer is likely to judge you and master JavaScript and DOM with the following 3 questions.
Let's get started! Note that we use native JavaScript in the following example, because interviewers often want to test your knowledge of JavaScript and DOM without the help of a library, such as JQuery.
Issue #1: Event Proxy
When you create an app, you sometimes need to add event listeners to the buttons, text, or pictures in the page, triggering certain actions when the user interacts with those elements.
As an example of a simple list of things to do, 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 might add an event listener to an element just like the following code:
Document.AddEventListener(' Domcontentloaded ', function () { let app = document . getElementById ( ' Todo-app ' ) ; let items = App . Getelementsbyclassname ( ' item ' ) ; //Add Event listener to each list item; for ( Let item of items ) { item . AddEventListener ( ' click ' , function () { alert ( ' clicked on item: ' + item . InnerHTML ) ; } ) ; &NBSP } } ) ;
Of course the above code can complete the interviewer's needs, the problem is that each list item will be added an event listener. There is no problem when there are only 4 items in the list, but if someone adds 10,000 items to the list of things to do (they may have a lot to do)? At that time, the function creates 10,000 event listeners and then adds them all to the DOM. This is very inefficient.
In the interview, it is best to ask the interviewer how many items a user can add. If there is never more than 10, then the code above will run without problems. But if the number of user input to-dos is not capped, then you need to change 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 clicks when the user is actually clicked. This is called an event proxy, which is more efficient than adding event listeners individually for each agent.
The following is the code for the event proxy:
Document.AddEventListener(' Domcontentloaded ', function () { let app = document . getElementById ( ' Todo-app ' ) ; //Add Event listener to Container app . AddEventListener ( ' click ' , function (e ) { if (E . Target && e . Target . nodeName = = = ' LI ' ) { < Span>let Item = e . Target ; alert ( ' clicked on item: ' + it Em . InnerHTML ) ; } } ) ; } )
Problem #2: Using closures in loops
Closures are often asked in interviews, as the interviewing faculties determine how familiar you are with the language by answering the question, and whether you know when to use closures.
A closure is an intrinsic function that can access a variable outside the scope of the function. Closures can be used for privatization and for creating factory functions. The common interview questions about closures are:
Write a function that loops an array of integers, delaying 3 seconds to print the index of each element in the array.
The common (incorrect) implementation of this problem is this:
const arr = [10, 12, 15, 21];for (var i = 0; i < arr.length; i++) { setTimeout(function() { console.log(‘The index of this number is: ‘ + i); }, 3000);}
If you run this function, you will find that 3 seconds after each print is 4, instead of the expected 0, 1, 2, 3.
In order to correctly find the cause of this situation, you need to understand how JavaScript runs this code, which is where the interviewer wants to see you.
The reason is that the setTimeout
function creates a function (closure) that accesses an external scope, which is the i
loop that contains the index. After 3 seconds, the function begins to execute i
the printed value, and at this point the loop ends, and i
the value is already 4. Because loop traversal 0, 1, 2, 3, 4 finally stopped at 4.
There are actually several ways to solve this problem correctly. There are two of them:
const ARR = [ ten , + , all , + ] ; For ( var i = 0 ; I < arr . length ; I + + ) { Pass the variable i to each function to give it access to the correct index setTimeout ( function (i_local ) { return function () { console . Log ( ' The index of this "is: ' + i_local ) ; } } (i< span>) , + ) ; }
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(‘The index of this number is: ‘ + i); }, 3000);}
Problem #3: debouncing (anti-jitter)
Some browser events can be triggered more than once in a short period of time, such as resizing a window or scrolling a page. If you add an event listener to the window scrolling event and the user keeps scrolling down the page quickly, your event may be triggered thousands of times within 3 seconds. This can lead to very serious performance problems.
If you discuss building applications, scrolling events, window adjustment events, or keyboard events during an interview, be sure to mention debouncing or throttling as a way to improve page speed and performance. Here's an example of a css-tricks:
In 2011, Twitter had a problem: when scrolling through Twitter summaries, the page became very jammed and even unresponsive. John Resig wrote a blog about the problem, explaining how bad it is to directly bind time-consuming functions to scroll
events.
Debouncing is a way to solve this problem by limiting the time interval that must elapse before the next function call. The correct way to implement debouncing is to synthesize several function calls once and only once after a given time has elapsed. Here is a native JavaScript implementation that uses scopes, closures, this, and timing events:
The Debounce function that will wrap the eventfunctionDebounce*f,, delay) { //Maintain a timer let timer = null ; //can access the closure of the timer return function () { //Gets the scope and variables of the function through ' this ' and ' arguments ' let Context = this ; , let args = arguments ; //If the event is called , clear timer and reset timer cleartimeout (timer ) ; timer = SetTimeout ( function () { &NBSP;FN . Apply (Context , args ) ; } , delay ) ; } }
This function-when passing in an event (FN)-is executed after a given time (delay).
The function uses this:
// 当用户滚动时被调用的函数function foo() { console.log(‘You are scrolling!‘);}// 在 debounce 中包装我们的函数,过 2 秒触发一次let elem = document.getElementById(‘container‘);elem.addEventListener(‘scroll‘, debounce(foo, 2000));
Throttling is a technique similar to debouncing, but it is not waiting for a period of time before calling a function, throttling is calling the function over a longer interval. So if an event is triggered 10 times every 100 milliseconds, throttling executes the function once every 2 seconds instead of 10 events within 100 milliseconds.
For more information on debouncing and throttling, please refer to the following articles and tutorials:
Throttling and debouncing in JavaScript
The difference between throttling and debouncing
Instance parsing throttling and debouncing
Throttling function call--remy Sharp
3 JavaScript Questions to note during an interview