Questions and answers for interviews frond-end developer Javascript

Lecture



1. How can I optimize the loading of external resources on the page?

      • Concatenation
      • Minification
      • Using CDN
      • Caching
      • etc.
  • 2 What is the advantage in uploading external resources from several domains?
    • How many resources can a browser download simultaneously from one domain?
  • 3 Name three ways to reduce page load time (perceived or real)

  • What tools do you use to test code performance?
    • JSPerf (http://jsperf.com/)
    • Dromaeo (http://dromaeo.com/)
    • etc.
  • What is FOUC (Flash Of Unstyled Content)? How to avoid it?
  • Tell us about your development environment (OS, editor, browser (s), other tools)
  • Describe the sequence of your actions when you create a new Web page.


Explain the difference between

<script>, <script async> и <script defer> 


Describe the request and response headers listed below:

Difference between:
- Expires, Date, Age and If-Modified- ...
- DNT
- Cache-Control
- Transfer-Encoding
- ETag
- X-Frame-Options

[⬆] JavaScript questions:

  • What js-libraries did you use?
  • Have you ever looked into the source code of libraries / frameworks that you used?
  • How is javascript different from java?
  • What is a hash table?
  • What are неопределенные (undefined) and необъявленные (undeclared) variables?
  • What is a closure and how / why is it used?
    • How do you prefer to use them?
  • Where are anonymous functions commonly used?
  • Explain the "JavaScript module pattern" and where it is applied
    • Bonus if the purity of the global namespace is mentioned
    • What if your module is not enclosed in a namespace?
  • How do you organize your code? (module pattern, inheritance)
  • What is the difference between host objects and native objects?
  • What is the difference between the last two lines:
  function Person () {}

 var person = Person ()
 var person = new Person () 
  • What is the difference between .call and .apply ?
  • What does Function.prototype.bind do and why?
  • When do you optimize your code?
  • Explain how inheritance works in JavaScript?
  • Where is document.write() still used?
    • Most generated banners, although not recommended
  • What is the difference between feature detection (detection of browser capabilities), feature inference (assumption of capabilities) and analysis of the user-agent string?
  • Tell us about AJAX in as much detail as possible.
  • Explain how JSONP works (and why this is not real AJAX)
  • Have you ever used JavaScript templating?
    • If yes, which libraries used? (Mustache.js, Handlebars etc.)
  • Explain what "hoisting" is
  • Explain event bubbling
  • What is the difference between an "attribute" and an "property"?
  • Why shouldn't I extend native JavaScript objects?
  • Why should I extend native JavaScript objects?
  • What is the difference between the document load and document ready events?
  • What is the difference between == and === ?
  • How to get parameters from the current window's URL?
  • Explain same-origin policy in the context of javascript
  • Explain event delegation
  • What patterns of inheritance in JavaScript do you know?
  • Make this code work:
  [1,2,3,4,5] .duplicator ();  // [1,2,3,4,5,1,2,3,4,5] 
  • Describe the principle of memoization (avoidance of repeated computations) in JavaScript
  • Why is the ternary operator so called?
  • What is the arity of a function?
  • What makes the line "use strict"; ? What are the advantages and disadvantages of using it?

[⬆] JavaScript code examples

  ~~ 3.14 

Question: What value does this offer return? Answer: 3

  "i'm a lasagna hog" .split (""). reverse (). join (""); 

Question: What value does this offer return? Answer: "goh angasal a m'i"

  (window.foo || (window.foo = "bar")); 

Question: What is window.foo? Answer: "bar" , only if the window.foo expression was false, otherwise the variable will retain its original value.

  var foo = "Hello";  (function () {var bar = "World"; alert (foo + bar);}) ();  alert (foo + bar); 

Question: What will these two alert show? Answer: "Hello World" and ReferenceError: bar is not defined

  var foo = [];
 foo.push (1);
 foo.push (2); 

Question: What is foo.length? Answer: 2

  var foo = {};
 foo.bar = 'hello'; 

Question: What is foo.length? Answer: undefined

[⬆] jQuery Questions:

  • Explain chaining.
  • Explain "deferreds".
  • What techniques do you know about optimizing jQuery code?
  • What does .end() do?
  • How to add a namespace to an event handler? What is it for?
  • What are the 4 different types of arguments that the jQuery () function takes?
    • Selector (string), HTML (string), Callback (function), HTMLElement, object, array, array of elements, jQuery object, etc.
  • What is fx queue?
  • What is the difference between .get() , [] , and .eq() ?
  • What is the difference between .bind() , .live() , and .delegate() ?
  • What is the difference between $ and $.fn ? What is $.fn ?
  • Optimize this selector:
  $ (". foo div # bar: eq (0)") 

write a closure example in javascript

If you are using JavaScript, but you haven’t figured it out to the end, what kind of a wonderful thing this connection is and why is it needed - this article is for you.

As is known, in JavaScript, the scope of local variables (declared by the word var) is the body of the function within which they are defined.

If you declare a function inside another function, the first one accesses the variables and arguments of the latter:
function outerFn (myArg) {
var myVar;
function innerFn () {
// has access to myVar and myArg
}
}
  At the same time, such variables continue to exist and remain accessible by an internal function even after the external function in which they are defined has been executed. 

Consider an example - a function that returns the number of own calls:
function createCounter () {
var numberOfCalls = 0;
return function () {
return ++ numberOfCalls;
}
}
var fn = createCounter ();
fn (); //one
fn (); // 2
fn (); // 3
  In this example, the function returned by createCounter uses the variable numberOfCalls, which stores the desired value between its calls (instead of immediately ending its existence with the return of createCounter). 

It is for these properties that such “nested” functions in JavaScript are called closures (a term that comes from functional programming languages) - they “close” to themselves the variables and arguments of the function within which they are defined.

Application closures


Let's simplify the example above a little bit - remove the need to separately call the createCounter function, make it anomimous and call immediately after its declaration:
var fn = ( function () {
var numberOfCalls = 0;
return function () {
return ++ numberOfCalls;
}
}) ();
  Such a construction allowed us to bind data to a function that persists between its calls — this is one of the uses of closures.  In other words, with the help of them we can create functions that have their changing state. 

Another good use of closures is the creation of functions, which in turn also create functions, something that some would call a so-called trick. metaprogramming. For example:
var createHelloFunction = function (name) {
return function () {
alert ( 'Hello,' + name);
}
}
var sayHelloHabrahabr = createHelloFunction ( 'Habrahabr' );
sayHelloHabrahabr (); // alerts “Hello, Habrahabr”
  Due to the closure, the returned function “remembers” the parameters passed to the function creating what we need for this kind of things. 

A similar situation arises when we do not return the internal function, but hang it on an event - since the event occurs after the function has completed, the closure again helps not to lose the data transmitted during the creation of the handler.

Consider a slightly more complicated example - a method that binds a function to a specific context (that is, an object that the word this will point to in it).
Function.prototype.bind = function (context) {
var fn = this ;
return function () {
return fn.apply (context, arguments);
};
}
var HelloPage = {
name: 'Habrahabr' ,
init: function () {
alert ( 'Hello,' + this .name);
}
}
//window.onload = HelloPage.init; // alert would be undefined, tk this would point to a window
window.onload = HelloPage.init.bind (HelloPage); // now everything works
  In this example, with the help of closures, a function bossed by the bind remembers the initial function and the context assigned to it. 

The next, fundamentally different application of closures is data protection (encapsulation). Consider the following construction:
( function () {
...
}) ();
  Obviously, inside the closure, we have access to all external data, but it also has its own.  Due to this, we can surround parts of the code with a similar construction in order to close local variables that have fallen inside from access outside.  (One of the examples of its use you can see in the source code of the jQuery library, which surrounds all its code with a closure, so as not to output the variables necessary only for it). 

There is, however, one trap associated with such an application - inside the closure the meaning of the word this is lost outside of it. It is solved as follows:
( function () {
// the higher this will be saved
}). call ( this );

Consider another trick from the same series. Everywhere it was popularized by the developers of the Yahoo UI framework, calling it “Module Pattern” and writing an entire article about it in the official blog.

Let us have an object (singleton) containing any methods and properties:
var MyModule = {
name: 'Habrahabr' ,
sayPreved: function (name) {
alert ( 'PREVED' + name.toUpperCase ())
},
sayPrevedToHabrahabr: function () {
this .sayPreved ( this .name);
}
}
MyModule.sayPrevedToHabrahabr ();
  With the help of a closure, we can make methods and properties that are not used outside the object private (i.e., accessible only to it): 
var MyModule = ( function () {
var name = 'Habrahabr' ;
function sayPreved () {
alert ( 'PREVED' + name.toUpperCase ());
}
return {
sayPrevedToHabrahabr: function () {
sayPreved (name);
}
}
}) ();
MyModule.sayPrevedToHabrahabr (); // alerts "PREVED Habrahabr"

Finally, I want to describe a common mistake that drives many into a stupor if they do not know how the closures work.

Let us have an array of links, and our task is to make sure that when clicked on each one, its serial number is displayed by an alert. The first decision that comes to mind looks like this:
for ( var i = 0; i <links.length; i ++) {
links [i] .onclick = function () {
alert (i);
}
}
  In fact, it turns out that when you click on any link, the same number is displayed - the value of links.length.  Why it happens?  In connection with the closure, the declared auxiliary variable i continues to exist, and at that moment when we click on the link.  Since by that time the cycle has already passed, i remains equal to the number of links - this is the value we see with clicks. 

This problem is solved as follows:
for ( var i = 0; i <links.length; i ++) {
( function (i) {
links [i] .onclick = function () {
alert (i);
}
}) (i);
}
  Here, using another closure, we “shade” the variable i, creating its copy in its local scope at each step of the cycle.  Thanks to this, everything now works as intended. 

Closing is one of the powerful expressive means of javascript, which is often neglected, and is not even advised to use.

Indeed, closures can lead to problems. But in fact, they are very convenient, just need to understand what is really happening.

Simply put, closure is an internal function. After all, javascript allows you to create functions during the execution of the script. And these functions have access to external function variables.

In this example, the inner function func , from inside of which both local variables and variables of the outer outer function are available:

01 function outer() {
02      var outerVar;
03
04      var func = function () {
05          var innerVar
06          ...
07          x = innerVar + outerVar
08      }
09      return func
10 }

When the outer function finishes working, the inner function func remains alive; it can be run elsewhere in the code.

It turns out that when you run func , the variable of the already-used outer function is used, that is, by the very fact of its existence, func closes the variables of the external function (or rather, all external functions).

Most often, closures are used to assign functions to event handlers:

1 function addHideHandler(sourceId, targetId) {
2      var sourceNode = document.getElementById(sourceId)
3      var handler = function () {
4          var targetNode = document.getElementById(targetId)
5          targetNode.style.display = 'none'
6      }
7      sourceNode.onclick = handler
8 }

This function takes two HTML element IDs and puts an onclick handler that hides the second element to the first element.

Those,

// при клике на элемент с ID="clickToHide"
// будет спрятан элемент с ID="info"
addHideHandler( "clickToHide" , "info" )

Here, the dynamically generated handler for the handler event uses the targetId from the external function to access the item.

.. If you want to go deeper and understand more ..

.. In fact, what is happening in the Javascript interpreter is much more complicated and contains much more details than described here ...

.. But in order to understand and use closures, it is enough to understand the internal mechanism of the functions, even if in such a simplified form in some places

Each execution of the function stores all variables in a special object with the code name [[scope]], which cannot be obtained explicitly, but it is   Questions and answers for interviews frond-end developer Javascript .

Each call to var ... just creates a new property of this object, and any mention of a variable is first searched for in the properties of this object.

This is the internal structure of the "scope" - is an ordinary object. All changes to local variables are changes to the properties of this implicit object.

Usually, after the function has completed execution, its scope is [[scope]] , that is, the entire set of local variables is killed.

The overall flow of execution looks like this:

01 // функция для примера
02 function sum(x,y) {
03      // неявно создался объект [[scope]]
04      ...
05      // в [[scope]] записалось свойство z
06      var z
07      // нашли переменную в [[scope]], [[scope]].z = x+y
08      z = x+y
09      // нашли переменную в [[scope]], return [[scope]].z
10      return z
11
12      // функция закончилась,
13      // [[scope]] никому больше не нужен и умирает вместе с z
14 }

By the way, for code outside the function (and generally global variables) the role of the [[scope]] container object is performed by the window object.

When one function is created inside another, it is passed a reference to an object with local variables [[scope]] external function.

Due to the existence of this link, the variables of the external function can be obtained from the internal function — by referring to its [[scope]] . First we search in ourselves, then in the external [[scope]] - and so on along the chain to the window object itself.

A closure is when an object of local variables [[scope]] external function remains alive after its completion.

An internal function can access it at any time and get the variable of the external function.

For example, let's analyze the work of the function that installs event handlers:

01 function addHideHandler(sourceId, targetId) {
02      // создан объект [[scope]] со свойствами sourceId, targetId
03
04      // записать в [[scope]] свойство sourceNode
05      var sourceNode = document.getElementById(sourceId)
06
07      // записать в [[scope]] свойство handler
08      var handler = function () {
09          var targetNode = document.getElementById(targetId)
10          targetNode.style.display = 'none'
11      }
12
13      sourceNode.onclick = handler
14
15      // функция закончила выполнение
16      // (***) и тут - самое интересное!
17 }

When you run the function, everything happens as standard:

  1. creates [[scope]]
  2. local variables are written there
  3. internal function gets reference to [[scope]]

But at the very end - the internal function is assigned to sourceNode.onclick . The external function has finished its work, but the internal one can start sometime later.

The javascript interpreter does not analyze whether the internal function will need variables from the external one, and which variables may be needed.

Instead, it simply leaves the entire [[scope]] external function alive.

So that when the internal function starts, if it suddenly does not find any variable in its [[scope]] , it could refer to the [[scope]] external function and find it there.

If an external function was created inside another (even more external) function, then another canned [[scope]] added to the chain, and so on to the global window .

In this example, the external function makeShout () creates an internal shout ().

01 function makeShout() { // (1)
02      var phrase = "Превед!" // (2)
03
04      var shout = function () { // (3,4)
05          alert(phrase)
06      }
07     
08      phrase = "Готово!" // (5)
09
10      return shout
11 }
12
13 shout = makeShout()
14 // что выдаст?
15 shout()

The shout () function on the rights of an internal function has access to the phrase variable. What value will it produce - the first or the second?

If it is not obvious, try reading this example before reading further.

And here is a detailed description of what is happening in the depths of javascript:

  1. Inside makeShout ()
    1. creates [[scope]]
    2. In [[scope]] is written: phrase="Превед!"
    3. In [[scope]] is written: shout=..функция..
    4. When created, the shout function receives a reference to the [[scope]] external function.
    5. [[scope]].phrase changed to the new value "Done!"
  2. When running shout()
    1. It creates its own object [[scope2]]
    2. Searches for phrase in [[scope2]] - not found
    3. Searches for phrase in [[scope]] external function - found the value "Done!"
    4. alert ("Done!")

That is, the internal function gets the last value of the external variables.

The closure allows you to create a summation function that works like this:

1 sum(a)(b) = a+b
2
3 // например
4 sum(1)(3) = 4

Yes, exactly: brackets are not typos.

And here is the sum function itself:

1 function sum(a) {
2    return function (b) {
3      return a+b
4    }
5 }

The addEvents function takes an array of div 's and puts each output of its number on onclick .

With the question "Why is this not working?" people usually start learning closures.

1 function addEvents(divs) {
2      for ( var i=0; i<divs.length; i++) {
3          divs[i].innerHTML = i
4          divs[i].onclick = function () { alert(i) }
5      }
6 }

For the test case, we will create 10 multicolored numbered div with different colors:

01 function makeDivs(parentId) {
02      for ( var i=0;i<10;i++) {
03          var j = 9-i
04          var div = document.createElement( 'div' )
05          div.style.backgroundColor = '#' +i+i+j+j+j+i
06          div.className= "closure-div"
07          div.style.color = '#' +j+j+i+i+i+j
08          document.getElementById(parentId).appendChild(div)
09      }
10 }

The button below will create 10 divs and invoke addEvents for them addEvents

If you call divs, they all give the same alert.

Such a glitch arose from the fact that all div[i].onclick get the value of i from one on all [[scope]] external functions. And this value ( [[scope]].i ) at the time of onclick processor activation is 10 (the cycle is completed as soon as i==10 ).

In order for everything to be in order, in such cases a special technique is used - the allocation [[scope]] . The following function works correctly. It is all the same, except div.onclick .

1 function addEvents2(divs) {
2      for ( var i=0; i<divs.length; i++) {
3          divs[i].innerHTML = i
4          divs[i].onclick = function (x) {
5              return function () { alert(x) }
6          }(i)
7      }
8 }

Now everything should be fine - each div gives an alert to its own number.

To assign div.onclick , the temporary function function(x) {..} run, which takes an argument x and returns a handler that takes x from the [[scope]] this time function.

The function(x) {..} entry is used to create the function, and then (i) to start with the argument i .

In general, javascript is a very convenient language in this sense. Allows any constructions, for example, instead of consecutive calls:

var f = function (a) { return [0, a, 2*a] }
var t = f(1)
var result = t[2] // 2

you can create a function in one line and immediately call a function and immediately get the 2nd element of the array:

var result = function (a){ return [0,a,2*a] }(1)[2]

The time function function(x) {..} finishes working right there, leaving in its [[scope]] correct value of x , equal to the current variable i loop.

When the handler is activated, the alert will take from the [[scope]] nearest external function and the correct x value.

In theory, these examples should be sufficient for understanding and practical use of closures.

You can also read about closures, for example, in article http://www.jibbering.com/faq/faq_notes/closures.html

Of course, the ECMA-262 language standard will make it possible to disassemble what is happening in all its details.

Explain Function.prototype.bind.

When do you optimize your code?

When would you use document.write ()?

The basics: closures, the difference between .call () and .apply () , as indicated by this , how prototype inheritance works.
Know ECMAScript 5: for example Object.create () , Object.defineProperty () , how methods like .map () , .filter () , .reduce () work .
Probably, you need to know the methods of working with page elements, the DOM3 standard, how to work so that there are no brakes.
How the page loads, at what point the scripts are executed, how to optimize the critical path. AMD and others like it.
Asynchronous programming, promises. (Especially if you intend to develop on node.js.)
Design patterns. Perhaps the advantage would be knowledge of frameworks like Backbone.js, Angular.js or React.js, although each of them has something to criticize.
Code profiling
Well, examples of your code: “show your github”


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone