Notes for the three JavaScript interviews

Source: Internet
Author: User
JavaScript is the official language of all modern browsers. Therefore, developers in various languages may encounter JavaScript problems during interviews. This article does not cover the latest JavaScript library, general development practices, or any new... JavaScript is the official language of all modern browsers. Therefore, developers in various languages may encounter JavaScript problems during interviews.

This article does not cover the latest JavaScript library, general development practices, or any new ES6 functions. Instead, we will talk about three JavaScript problems that often occur during interviews. I asked these questions, and my friends said they also asked.

Of course, it doesn't mean that you only need to learn these three questions when preparing for a JavaScript interview-you still have many ways to better prepare for the upcoming interview-but the interviewer is likely to judge through the following three questions: you understand and understand JavaScript and DOM.

Let's get started! Note that we use native JavaScript in the following example, because the interviewer usually wants to examine your understanding of JavaScript and DOM without the help of libraries (such as jQuery.

Question #1: Event proxy

When creating an application, you sometimes need to add event listeners to buttons, text, or images on the page. Some operations are triggered when the user interacts with these elements.

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

 
 
  • Walk the dog
  • Pay bills
  • Make dinner
  • Code for one hour

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

Document. addEventListener ('domainloaded', function () {let app = document. getElementById ('todo-app'); let items = app. getElementsByClassName ('item'); // Add an event listener for (let item of items) {item. addEventListener ('click', function () {alert ('You clicked on item: '+ item. innerHTML );});}});

Of course, the above Code can fulfill the interviewer's needs. The problem is that an event listener is added to each list item. If there are only four items in the list, but if someone adds 10,000 items to the list (they may have a lot to do )? Then the function creates 10,000 Event Listeners and adds them to the DOM. This is very inefficient.

In the interview, you 'd better first ask the interviewer how many agents a user can add at most. If there will never be more than 10, then the above Code runs well. However, if the number of to-do items you enter is not limited, you have to change to a more efficient solution.

If the application has hundreds of event listeners, a more efficient solution is to addOneEvent listener. When a user clicks the event, the event handler obtains the actual event. This is called an event agent, which is more efficient than adding an event listener to each agent.

The following is the event proxy code:

Document. addEventListener ('domainloaded', function () {let app = document. getElementById ('todo-app'); // Add the event listener app to the container. addEventListener ('click', function (e) {if (e.tar get & e.tar get. nodeName = 'lil') {let item = e.tar get; alert ('You clicked on item: '+ item. innerHTML );}});});
Question #2: Use a closure in a loop

Closures are often asked during interviews, because the interviewer can use the answers to this question to determine your familiarity with the language and whether you know when to use the closure.

Closures are internal functions that can access external variables in the scope. Closures can be used to achieve privatization and create factory functions. The common questions about closures are as follows:

Write a function, loop through an integer array, and wait 3 seconds to print the index of each element in the array.

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('The index of this number is: ' + i);  }, 3000);}

If you run this function, you will find that4Instead of the expected0, 1, 2, 3.

To find out the cause of this situation correctly, you need to understand how JavaScript runs this code. This is what the interviewer wants to know about you.

The reason is that the setTimeout function creates a function (closure) that accesses the external scope, which is the loop containing index I. 3 seconds later, the function starts to print the I value, and the loop ends, and the I value is already 4. Because the loop traversal stops at 4 after 0, 1, 2, 3, and 4.

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

Const arr = [10, 12, 15, 21]; for (var I = 0; I <arr. length; I ++) {// input the variable I to each function so that it can access the correct index setTimeout (function (I _local) {return function () {console. log ('the index of this number is: '+ I _local) ;}} (I), 3000 );}
Const arr = [10, 12, 15, 21]; for (let I = 0; I <arr. length; I ++) {// use the let keyword in ES6, which creates a new binding when a function call // learn more: http://exploringjs.com/es6/ch_variables.html#sec_let-const-loop-heads setTimeout (function () {console. log ('the index of this number is: '+ I) ;}, 3000 );}
Question #3: Debouncing (Anti-jitter)

Some browser events can be triggered multiple times in a short period of time, such as adjusting the window size or scrolling the page. If you add an event listener to The Window Rolling event and the user keeps scrolling down the page, your event may be triggered several thousand times within 3 seconds. This can cause very serious performance problems.

If you discuss building applications, rolling events, window adjustment events, or Keyboard Events during the interview, make sure to mention debouncing or throttling as a way to improve the page speed and performance. Here is an example of css-tricks:

In 2011, Twitter encountered a problem: when the Twitter abstract was rolled, the page became very slow or even unresponsive. John Resig wrote a blog about this issue, explaining how bad it is to bind time-consuming functions directly to a scroll event.

Debouncing is a way to solve this problem. It restricts the time interval that must be waited before the next function call. The correct debouncing method is to call several functions.SynthesisAnd is called only once after a given time. The following is a native JavaScript implementation that uses the scope, closure, this, and timing events:

// The debounce function of the event will be wrapped in the debounce (fn, delay) {// maintain a timer let timer = null; // can access the closure of the timer return function () {// obtain the function scope and variable "let context = this; let args = arguments" Through 'eas' and 'arguments'; // if the event is called, clear timer and reset timer clearTimeout (timer); timer = setTimeout (function () {fn. apply (context, args) ;}, delay );}}

This function-when an event (fn) is passed in-will be executed after the specified time (delay.

The function is used as follows:

// Function foo () {console. log ('You are scrolling! ');} // Wrap our function in debounce and trigger let elem = document once in 2 seconds. getElementById ('Container'); elem. addEventListener ('scroll ', debounce (foo, 2000 ));

Throttling is similar to debouncing, but it does not wait for a while before calling a function. throttling calls a function within a long interval. Therefore, if an event is triggered 10 times per 100 milliseconds, throttling will execute this function once every 2 seconds instead of 10 events within 100 milliseconds.

The above are the details of the three questions that need to be paid attention to during the JavaScript interview. For more information, see other related articles in the first PHP community!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.