📜 ⬆️ ⬇️

Javascript: 12 questions and answers

JavaScript is a terrific tool that can be found literally in every corner of the modern Internet. But even despite its incredible prevalence, and professionals in the field of JS will always have something to learn. There is always something that they do not know.

image

In this article you will find an analysis of twelve questions about JavaScript, which even experienced developers often cannot answer. We will first look at ten typical questions, including those that often come up during interviews. The remaining two questions are devoted to more complex and ambiguous things, in particular, using JS to improve the performance of web pages and develop applications that do not lose relevance over time.

Question number 1. What is prototype inheritance?


Almost everything in JavaScript is objects. Each object has a prototype from which it inherits properties and methods. If the object does not include the requested property, JavaScript will search for this property in the object's prototype. In this case, the search will be performed on a chain of prototypes until you find what you need. If the search fails, an error will be returned.
')
Prototypes are very useful for creating objects that have the same properties and methods. When all this is defined at the prototype level, only one copy of such entities is required, which leads to efficient use of memory.

var parent = {inherit: true} var childA = Object.create(parent); var childB = {}; Object.setPrototypeOf(childB, parent); class childC extends parent {} 

Prototypes can be added to objects when creating these objects, using the Object.create() command, or after creation, by the Object.setPrototypeOf() command. The ES2015 standard provides for the class keyword, it also has the extends command, which allows you to use the value specified when it was called as a prototype object.

Question number 2. How can javascript be used to increase the availability of web projects?


Modern tools for ensuring the accessibility of websites for people with disabilities often know how to handle JavaScript and dynamic page content. Both JS and dynamic data can be docked with accessibility tools, while keeping in mind that in this case it’s best when, for example, scripts are used as tools for extending project functionality rather than certain features that are absolutely necessary for it to work properly.

The usual way to help users work with the site is to provide convenient means to navigate through the objects of the pages with which you can interact. It's about focus management. For example, if a calendar appears on a page, the user should be able to use it without a mouse, in particular with the arrow keys. Namely, the left and right navigation arrows can be used (provided that seven days are displayed in one line of the calendar screen display) to go by day, and the keys to go up and down to switch between weeks. This is done by listening to keyboard events while the calendar is getting focus.

If changing important data is implemented by JavaScript, for example, when filling out a feedback form, new data should be passed to the screen reader. Often this is accomplished by marking the corresponding container as an interactive area.

Question number 3. What is event float and how does it differ from event capture?



Event popup is used when implementing event delegations. If you subscribe to the events of the parent element, you can get information about the events and for its descendants

Both interception and ascent of events are part of a process called “event distribution”, during which the browser responds to events occurring on the page. Older browsers performed either one or the other, but nowadays all browsers support both interception and the emergence of events.

The first phase, the interception phase, is executed immediately after the event occurs. The event starts at the topmost level, which is either a document object or a window object depending on the event. From here it is omitted, passing through the <html> and through what is in this tag, until it reaches the element within which it originated.

Then the second phase occurs - the ascent of the event. In its course, the same process is repeated, but vice versa. It all starts with the element that triggered the event, it “pops up” to the root element <html> . When adding event listeners, this is the behavior expected for the system.

Question number 4. How does event delegation improve code on sites with a lot of interactive elements?


Websites are often full of dynamic elements that are constantly changing. If such elements must also be interactive, you will need some way of observing the events that occur when the user interacts with them. If each element needs its own event listener, it will litter the code and increase the load on the browser.

Event delegation is a technique that uses the event bubbling mechanism. By adding a listener to the parent element, the developer can adjust event handling for his descendants.

 parentEl.addEventListener('click', function(e) { if(e.target && e.target.nodeName == 'BUTTON') { //    } }); 

Inside the event listener callback function, the target element of the event will be represented by the target parameter, which can be used to decide on further actions. For example, the attribute of this data parameter may store an identifier for accessing properties of an object.

Question number 5. What are closures and how can they help code organization?


Functions in JavaScript use what is called "lexical scope". This means that they have access to variables defined in the scope that includes them, but those variables that are declared inside functions are not accessible from the outside.

 function outer() { let x = 'Web Designer'; function shout() { alert(`I love ${x}!`); } shout(); } 

Calling the outer() function will display the message “I love Web Designer!”, But if you try to access the shout() function or the x variable outside of the outer() function, it turns out that both are not defined. A closure is a combination of a function and its lexical environment. In our example, the closure is the function outer() .

Closures are useful when creating large sets of components, since everything declared inside one closure does not affect others. Closures can be used to create private functions and variables in ways similar to those used in other object-oriented languages ​​like Python. The “module” template makes extensive use of closures to provide structured ways for modules to interact.

Question number 6. What does the line 'use strict' at the top of the code block mean?


ES5 describes a special version of JavaScript, called strict mode (strict mode). In strict mode, the use of ambiguous constructs from earlier versions of the language causes errors instead of leading to unplanned behavior.

 function strictFunction() { 'use strict'; myVar = 4; //ReferenceError } 

In the code snippet above, we are trying to assign a value to an undeclared variable. Outside of strict mode, the execution of such a command will result in the addition of the variable myVar to the global scope, which, if you do not pay enough attention to such things, can completely change the functionality of the script. In strict mode, this results in an error message and thus prevents a possible disruption of the program. The ES2015 modules use strict default mode, but in closures created using functions, the 'use strict' command can be used at the function level, as well as at the entire file level.

Question number 7. What does the term "raising variables" mean when applied to JavaScript?


One of the features of JavaScript is the fact that programs written on it are distributed in an uncompiled form. The browser compiles the scripts, as they say, on the fly, and during this process takes notes on the functions and variables declared in these scripts.

After the first viewing of the code, the browser performs the second pass, which is the execution of the program, already knowing where functions and variables are applied. When executing a code snippet, declarations of functions and variables “rise” to the top of this fragment.

 welcome("Matt"); //"Welcome, Matt." function welcome(name) { return `Welcome, ${name}.`; } 

In this example, the welcome() function can be used before its declaration in the code, since it “rises” to the top of the script.

Question number 8. How do arrow functions differ from ordinary functions?


Many changes have appeared in ES2015, and one of them, quite noticeable, was the introduction of switch functions.

 function CountUp() { this.x = 0; setInterval(() => console.log(++this.x), 1000); } var a = new CountUp(); 

The main difference between the switch functions and the usual functions, even if you don’t look at what they are shorter, is that the switch functions do not define an eigenvalue for this . Instead, they use the value of this block in which they are included. In the above example, when this.x numbers 1, 2, 3, and so on will be displayed every second. When used in a similar situation with a regular function, this would be undefined , which would lead to NaN output. The body of the arrow function is its return value. This makes it particularly convenient to use switch functions in promises. Ordinary functions, unlike pointer ones, must explicitly return some value, otherwise undefined will be automatically returned.

Question number 9. In what situations should the keywords let and const be used?


Another fundamental innovation in ES2015 was the introduction of the let and const keywords as alternative ways to declare variables. The scope of such variables is limited to the block in which they were declared. This gives more confidence that variables created in different blocks of code will not affect what is outside of these blocks.

 for(let x=1; x<=3; x++) { console.log(x); // 1, 2, 3} console.log(x); // "x is not defined" 

If the value of a variable does not change during program execution, use const instead of let . An attempt to redefine such a variable, which is more correctly called a "constant", will generate an error. It should be borne in mind that with this approach, the internal contents of objects and arrays, references to which are written in constants, may change, but they cannot be replaced with new objects.

Variables declared using let and const are not raised, unlike variables declared using the var keyword, so they cannot be accessed before they are initialized. The space between the beginning of a block of code and the place of initialization of a variable is known as the “temporary dead zone,” which can often be the cause of confusion.

Question number 10. What is functional programming and what are its features?



Net function

Functional programming is an approach to the development of programs, the essence of which is that the data representing the state of the application are processed exclusively with the help of functions. If such functions do not produce side effects, the result is a code that is easy to work with and easy to understand.

Usually JS-projects are built using the principles of object-oriented programming. Information about the current state of the program is stored in objects, and if something changes on the page, information about changes is recorded in these objects.

Functional programming is, in fact, a different style of thinking. I must say that languages ​​like F # have used similar principles for a very long time. At the same time, in ES2015, some important mechanisms appeared that extend the possibilities of functional programming on JS.

If, in developing a web project, to follow the rules of functional programming, then you need to take into account that all operations must be carried out inside the so-called "clean" functions. These are functions that are not affected by data that is outside the scope of these functions. In other words, when such a function is betrayed by the same data, it must always return the same result.

In addition, this means that functions should not have shared access to some external data in relation to them, for example, representing the state of the application. If an application needs to change its state, it should pass it to the function as a parameter.

Finally, in the code, you should avoid changing the existing values. For example, when performing operations that involve modifying objects, copies of these objects with modified values ​​should be returned. This helps to get rid of side effects that lead to errors and complicate code testing.

Question number 11. How to use javascript to improve webpage performance?


Today, the majority of web page views are performed from smartphones or tablets. In this case, not everyone has the most modern devices. Therefore, how quickly the pages respond to user actions is very important. Any "brakes" in the work of the site can result in the loss of a client. Fortunately, in JavaScript there are tools that help to avoid this.

â–Ť Avoid unnecessary effects on page scrolling.


“Ragged” scrolling is a clear sign that some program actions are being performed on the page. In some cases, the browser has to wait due to the fact that there are some event listeners on the page. Thus, events such as wheel or touchmove can cancel scrolling, as a result, the page has to wait until the event is completed before the standard scrolling behavior begins.

This can lead to jumps when scrolling the page and to its unstable speed, which causes users to have bad impressions of working with the page.

 document.addEventListener('touchmove', handler, {passive: true}); 

To avoid this, by adding an event listener, pass to it, as a third parameter, an object with the passive property set to true . The browser, working with a similar event, may assume that it does not affect scrolling, as a result, the page scrolling can start without unnecessary delays.

The third parameter replaces the useCapture option in older browsers, so before applying this or that approach, you need to check what the browser supports. In order to intentionally disable the interaction of a certain area with the user, in most browsers you can use touch-action: none in CSS.

â–Ť Throttle events


Events, such as scrolling or resizing an element, occur as quickly as possible, so that all listeners get the actual data. If some resource-intensive operations are performed during the processing of each event, this can quickly lead to a page freeze.

 const resizeDebounce = debounce(() => { //       }, 200); window.addEventListener('resize', resizeDebounce); 

Eliminating the "bounce" of events is a technique that reduces the frequency of calling event-handling functions that occur too often. The implementation of this mechanism, as well as the frequency of calling functions in different projects vary, however, it can be noted that reducing the frequency of event processing to five times per second, for example, leads to an immediate improvement in page performance.

▍ Visible area of ​​the page


A typical way to use scrolling events is to detect when an element is visible on the page. Even with the use of the bounce technique, the getBoundingClientRect() call requires the browser to analyze the layout of the entire page. There is a new browser API, called IntersectionObserver , that reports on the state change of elements that are monitored by means, calling a given function every time they enter or leave the viewport. For pages with endless scrolling, this API can be used to mark obsolete visual elements as suitable for deletion or reuse.

The IntersectionObserver API is available in all recent browsers with the exception of Safari. At the same time, the difference between using the new method of working with the page view area and the old approaches to determining the visibility of elements is quite noticeable.

â–ŤAllocation of resource-intensive operations into separate flows


When working with large data sets or processing large files, such as images, JavaScript can block the browser window. By default, all tasks are performed in a single thread, so if this thread is overloaded, the application interface will no longer respond to user input.

If you know that it will take a long time to perform a certain operation, it would be nice to think about putting it into a web worker. So called scripts that run in separate threads, while even if these scripts perform resource-intensive operations, the user interface of the web application continues to work. Such scripts can transfer data to each other using a special messaging mechanism. Web workers do not have access to the DOM and to some properties of the window object; message exchange mechanisms are also used to transfer data to the main stream that can affect the interface.

Question number 12. How to write JS-code that does not lose relevance over time?


One of the basic principles of JavaScript is that in the course of its development, they try not to make, if feasible, changes that make it impossible to execute code written for its previous versions. As a result, for example, virtually all code written today will work a decade later, even taking into account the variability of the web development world.

However, the fact that a certain code fragment is executed does not mean that it will not lose relevance over time. It’s time to ask how your post will look today in a few years. Here are some guidelines that will allow you to create programs that are ready for the test of the future.

â–Ť Avoid spaghetti code


At the initial stages of working on a certain project, it may seem an attractive idea, so to speak, “to throw everything into one pile” without breaking the code into small, fairly independent parts. Although with this approach it is easy to understand what is being done in a particular code fragment, it also means that the functionality of the program is closely related to each other. So, if somewhere in the program you need something that is implemented in another part of it, the corresponding section of the code is copied, and possibly rewritten, taking into account the new needs. , , , , , , -, .

, , , . , . , «», , , .

â–Ť


, React Polymer, . .

, « »? , , . , , .

, , , , , JavaScript. . , , , .

, . , , , API, , , , Node.

â–Ť


, , , . , , , , , , .

 let activeUsers = users.filter(user => user.active === true); 

, , , . , , , - i j , .

, , . , . , ESLint, .

â–Ť


, , . . , , , .

, , , . , , , .

, , , . , , , . , , , users , . , , , . , , . , - . — «» , .

â–Ť ,



Jest , ,

React , . , , , , . — , , , .

. Mocha Jest , . .

, . , , , .

, , . , . — .

â–Ť



Babel

, — . , « », , , , .

, , Babel — , JavaScript . , JS.

ES2015 JS , , . — , . , ES2017, , , , . Babel, , , .

, JS , , , , , .

Results


JavaScript, - , , , , . , , , .

Dear readers! , JS-, , , . -, ?

Source: https://habr.com/ru/post/346022/


All Articles