Interview javascript. What will be output to the console? Explain why. General programming questions

As much as you like.

  • You need to display some kind of message as an alert, 3 seconds after the script is launched. How to do it?

So:

Or like this:

  • How is inheritance in JavaScript different from inheritance in PHP?

Unlike PHP, where inheritance can be done in one way, in JavaScript there are many such ways. At the language level, inheritance on prototypes is implemented.

In JavaScript, each object can have an association with another object - the so-called "prototype". In case the search for some property (or method) in original object ends unsuccessfully, the interpreter tries to find the property (method) of the same name in its prototype, then in the prototype's prototype, etc. For example, if we requested a call to obj.prop (or, which is absolutely the same, obj["prop" ]), JavaScript will start looking for the prop property in obj itself, then in the prototype of obj, the prototype of the prototype of obj, and so on until the end.

  • Give an example of inheritance in JavaScript.

For example, let the object "cat" inherit from the object "animal".In inheritance on prototypes, this is implemented as a reference

Or here's a slightly more detailed example. MyType inherits from Obj:


  • A few words about objects in JavaScript?

Objects (they are also associative arrays, hashes) and working with them in JavaScript are implemented differently than in most languages. An object in JavaScript is a regular associative array or, in other words, "hash". It stores any key => value matches and has several standard methods.

  • What is an object method in JavaScript?

An object method in JavaScript is simply a function that is added to an associative array.

  • Why write var before a variable in JavaScript?

If you create a variable through a regular assignment, a “global variable” will be created. Example:

If you create a variable using the word var, then a "local variable" will be created, which ceases to exist when the function completes. Example:

  • There are two functions:function f(a,b) ( return a+b ) And var f = function(a,b) ( return a+b ).Is there a difference between them? If so, which one?

There is a difference in the visibility of the function. The non-var version of the function is visible everywhere in the current scope. Including the very definition of the function. The var option assigns a function to a variable, so the function is only visible after it is defined.

  • How to create an array in JavaScript?

Here are some ways.

  • Is it possible to use a function as a constructor in JavaScript?

Like this:

  • How many and what looping constructs are there in JavaScript?

Three: for, while and do...while.

  • What the code will do: break mark; ?

Will exit the current loop or switch block at the " mark ".

  • Is it possible to define an array like this: var a = "a,b".split(",")?

Yes, you can.

  • What does alert(typeof null); ?

Will display the message "object".

  • And this is: alert(null instanceof Object); ?

Will display the message "false".

  • 0.1 + 0.2 == 0.3 ?

No, because the calculated value will be 0.300000000000000004. This is the effect of computational precision and is not limited to JavaScript.

  • What does alert(typeof NaN); ?

"Number"

  • What will the output be alert(NaN === NaN); ?

"false"

  • What is the difference between innerHTML and outerHTML properties?

The innerHTML property of any DOM element contains the HTML code that is inside that element. When setting a new value for this property, inner HTML the code is rendered again by the browser.

outerHTML is almost the same as innerHTML, the difference is what it returns full HTML element.

Also, it is important to note that innerHTML is supported by all modern browsers, and outerHTML is supported in IE (with some differences from other browsers), in latest versions Opera, and in browsers based on the latest WebKit (Safari, Chrome), but is not supported in Firefox.

For the code:

innerHTML will return:

outerHTML will return:


  • What's the difference between the == and === operators?

The == operator compares for equality, but === compares for identity. The advantage of the === operator is that it does not cast two values ​​to the same type. This is why it is commonly used.

  • What is the difference between Object.getOwnPropertyNames() and Object.keys()?

Object.getOwnPropertyNames() returns enumerable and non-enumerable properties from an object or array.

Object.keys() returns enumerable properties from an object or array.

  • Which language construct can be used to control the flow of a script and track errors?

This is possible using the try()... catch() construct

  • Why call a(); happens successfully, and the call b(); gives an error message?

Function a() is initialized at the script loading stage, as if it “pops up”, and function b is initialized when the variable b is declared

  • What are global variables? How are they created? What are the problems with using global variables?

A global variable is a variable that is available (visible) throughout the entire document, as opposed to a local variable (limited within the block program code, within which it is defined)

Majority JavaScript developers avoids the use of global variables. One of the reasons - possible conflict names of global and local variables. Also, code that uses global variables can be more difficult to maintain and test.

  • What are closures in JavaScript?

In simple words this is internal function, i.e. function within a function.

They call it a closure because after the parent or external function, the internal code still "lives" in the interpreter and can be executed. No errors will occur even if the inner function (closure) uses variables from the outer function.For example, this feature can be used to create event handler functions:


  • Write a function that takes a string with the file name and returns the extension (the fragment after the last dot).

    • What is prototype in javascript?

    IN general outline prototype is a property that allows you to add properties to existing objects; it is also used to emulate class inheritance in JavaScript. A detailed answer is written here. Another option is to mention Prototype.js. This is a popular library that adds convenient OOP capabilities to JavaScript programs.

    • What methods of attaching event handlers do you know?

    Events can be added in three ways:

    • htmlElement.onclick = function(event) ( .... ) - this way you can add only one handler
    • htmlElement.addEventListener("click", ...) - this way you can attach several handlers, preserves the order of the handlers
    • htmlElement.attachEvent("on"+event_name, handler) - you can also attach several, does not preserve the order of handlers, there is no access to the element on which the event was triggered.

As much as you like.

  • You need to display some kind of message as an alert, 3 seconds after the script is launched. How to do it?

So:

Or like this:

  • How is inheritance in JavaScript different from inheritance in PHP?

Unlike PHP, where inheritance can be done in one way, in JavaScript there are many such ways. At the language level, inheritance on prototypes is implemented.

In JavaScript, each object can have an association with another object - the so-called "prototype". If the search for a certain property (or method) in the source object fails, the interpreter tries to find the property (method) of the same name in its prototype, then in the prototype's prototype, etc. For example, if we requested a call to obj.prop (or, which is exactly the same thing, obj["prop"]), JavaScript will start looking for the prop property in the object obj itself, then in the prototype of obj, the prototype of the prototype of obj, and so on until the end.

  • Give an example of inheritance in JavaScript.

For example, let the object "cat" inherit from the object "animal".In inheritance on prototypes, this is implemented as a reference

Or here's a slightly more detailed example. MyType inherits from Obj:


  • A few words about objects in JavaScript?

Objects (they are also associative arrays, hashes) and working with them in JavaScript are implemented differently than in most languages. An object in JavaScript is a regular associative array, or, in other words, a "hash". It stores any key => value matches and has several standard methods.

  • What is an object method in JavaScript?

An object method in JavaScript is simply a function that is added to an associative array.

  • Why write var before a variable in JavaScript?

If you create a variable through a regular assignment, a “global variable” will be created. Example:

If you create a variable using the word var, then a "local variable" will be created, which ceases to exist when the function completes. Example:

  • There are two functions:function f(a,b) ( return a+b ) And var f = function(a,b) ( return a+b ).Is there a difference between them? If so, which one?

There is a difference in the visibility of the function. The non-var version of the function is visible everywhere in the current scope. Including the very definition of the function. The var option assigns a function to a variable, so the function is only visible after it is defined.

  • How to create an array in JavaScript?

Here are some ways.

  • Is it possible to use a function as a constructor in JavaScript?

Like this:

  • How many and what looping constructs are there in JavaScript?

Three: for, while and do...while.

  • What the code will do: break mark; ?

Will exit the current loop or switch block at the " mark ".

  • Is it possible to define an array like this: var a = "a,b".split(",")?

Yes, you can.

  • What does alert(typeof null); ?

Will display the message "object".

  • And this is: alert(null instanceof Object); ?

Will display the message "false".

  • 0.1 + 0.2 == 0.3 ?

No, because the calculated value will be 0.300000000000000004. This is the effect of computational precision and is not limited to JavaScript.

  • What does alert(typeof NaN); ?

"Number"

  • What will the output be alert(NaN === NaN); ?

"false"

  • What is the difference between innerHTML and outerHTML properties?

The innerHTML property of any DOM element contains the HTML code that is inside that element. When you set a new value for this property, the internal HTML code is re-rendered by the browser.

outerHTML is almost the same as innerHTML, the difference is that it returns the full HTML of the element.

Also, it is important to note that innerHTML is supported by all modern browsers, and outerHTML is supported in IE (with some differences from other browsers), in the latest Opera versions, and in browsers based on the latest WebKit (Safari, Chrome), but is not supported in Firefox.

For the code:

innerHTML will return:

outerHTML will return:


  • What's the difference between the == and === operators?

The == operator compares for equality, but === compares for identity. The advantage of the === operator is that it does not cast two values ​​to the same type. This is why it is commonly used.

  • What is the difference between Object.getOwnPropertyNames() and Object.keys()?

Object.getOwnPropertyNames() returns enumerable and non-enumerable properties from an object or array.

Object.keys() returns enumerable properties from an object or array.

  • Which language construct can be used to control the flow of a script and track errors?

This is possible using the try()... catch() construct

  • Why call a(); happens successfully, and the call b(); gives an error message?

Function a() is initialized at the script loading stage, as if it “pops up”, and function b is initialized when the variable b is declared

  • What are global variables? How are they created? What are the problems with using global variables?

A global variable is a variable that is available (visible) throughout the document, as opposed to a local one (limited by the block of program code within which it is defined)

Most JavaScript developers avoid using global variables. One of the reasons is a possible conflict in the names of global and local variables. Also, code that uses global variables can be more difficult to maintain and test.

  • What are closures in JavaScript?

In simple words, this is an internal function, i.e. function within a function.

They call it a closure because after the parent or outer function is executed, the inner code still “lives” in the interpreter and can be executed. No errors will occur even if the inner function (closure) uses variables from the outer function.For example, this feature can be used to create event handler functions:


  • Write a function that takes a string with the file name and returns the extension (the fragment after the last dot).

    • What is prototype in javascript?

    In general terms, prototype is a property that allows you to add properties to existing objects, and is also used to emulate class inheritance in JavaScript. A detailed answer is written here. Another option is to mention Prototype.js. This is a popular library that adds convenient OOP capabilities to JavaScript programs.

    • What methods of attaching event handlers do you know?

    Events can be added in three ways:

    • htmlElement.onclick = function(event) ( .... ) - this way you can add only one handler
    • htmlElement.addEventListener("click", ...) - this way you can attach several handlers, preserves the order of the handlers
    • htmlElement.attachEvent("on"+event_name, handler) - you can also attach several, does not preserve the order of handlers, there is no access to the element on which the event was triggered.

The week of interviews on Habré has passed, but I decided to finish off the still living respected reader with an article in which I will share some of the tasks that employers gave me during interviews over the course of last month(among them are Yandex, Topface, ITMozg, a couple of very interesting and a couple of rather murky startups).

Of course, you won't be able to ace an interview simply by memorizing the answers to these questions. The answer to each question will need to be explained, sometimes in great detail. Many questions will be further supplemented by the interviewers. I ask you to consider these questions as a kind of “bar” that you need to achieve on your own in order to become a Junior in a good company.

Actually, the tasks themselves

1

Imagine that we have a square grid field on which a tramp walks.
Write a "Tramp" object containing its coordinates and four methods that implement the tramp's steps up, down, right, and left.
How to implement a chain like this in such an object:

Vagabond.goUp().goLeft().goDown().goDown().goRight();

2

There is an array of arbitrary length, filled with random values:

Var list = ;

you need to find the value of the maximum element.

3

It is necessary to send a set of data to the server without reloading the page. List ways to do this, name the most cross-browser one.

4

What is the difference between duck == and === ?

5

What are Local Storage, Cookies and Session Storage? What is the difference between them?

6
@media only screen and (max-width: 1200px) ( )

What kind of design is this? Why might it be needed?

7

What is the difference between merge and rebase in Git?

8

Var a = new F(); var b = new F(); alert(a == b); function F() ()

Make a == b return true .

9

Write the results of the operations:

"1" + 2; 1 + "2"; null == undefined; null == 0; null > 0; null >= 0; "a" > "A";

10

Var list = ; function sum() ( var sum = 0; for (i=0; i

11

Imagine a large and complex page that loads very slowly. Let's say everything is bad on her. Your task is to optimize loading time. Your actions?

Conclusion

Almost all tasks had to be completed orally or in the good old IDE “Paper & Pencil”. Nobody demanded bugless code. Those who were more adequate were primarily interested in the train of thought, and not in knowledge of the intricacies of technology. But, of course, the level of knowledge of HTML, JS and CSS also matters (as you wish). Interviews in some cases are more reminiscent of an exam with good teachers (this was the case at ITMozg and Topface), in some - a pleasant friendly conversation with tea drinking (Yandex, Radario), and in some - the devil knows what (I won’t name the companies, besides however, they are little known).

If any of the readers, after reading this, come up with the thought “It turns out that there is nothing to be afraid of during interviews even at the coolest companies. Working in Yandex and Topface is within reach,” which means I didn’t write this in vain.

Thank you for your attention. Good luck to all.

During interviews, people often like to ask the same type of questions, the answers to which have long been learned.

Today we will consider those issues that are rarely mentioned.

So, let's begin!

1. What is foo.x equal to?

var foo = (n: 1);
var bar = foo;
foo.x = foo = (n: 2);

This question is asked by the top 3% of companies (Apple, Google, Facebook).

The main thing to note here is that the foo referenced by foo.x is “set” before foo changes. foo.x refers to the old value of foo.

  • Let's lref be the result of evaluating LeftHandSideExpression.
  • Let's rref be the result of evaluating AssignmentExpression.

This means that in the old foo there will be a new property x equal to (n: 2) . And the new foo will be written (n: 2) .

The value of the old foo is in bar:

//bar
{
n: 1,
x: (
n: 2
}
}

Since in the further output of foo.x our foo refers to its new value, in which x is missing, then accordingly foo.x will be undefined.

Answer: undefined

2. Write an addition function of the form add(num1)(num2)..

Note: The number of terms is not limited

In the original, this problem is solved this way:

Const add = (a) => (
let sum = a;
const func = (b) => (
if (b) (
sum += b;
return function;
) else (
return sum;
}
};
return function;
);

add(2)(3)(); // 5;

But then they give you one condition.
Remove extra parentheses at the end

add(2)(3) // 5 add(1)(2)(5) // 8 ... Now the task has become more difficult. And the solution lies in overriding the method

Const add = (a) => (
let sum = a;
const func = (b) => (
sum += b;
return function;
};
valueOf.
func.valueOf = () => sum;

return function; ); console.log(add(2)(3)); // 5; When we call console.log he expects to see.

In the example above, after executing add(2)(3), a function is returned, which console.log will turn into a String, during these actions the valueOf method will be called to convert the function to a primitive, and since we have overridden this method, it will return our value sum instead of the standard one.

Note:

This example doesn't work for everyone. console.

3. What will be displayed in the console? Explain why.

var a=(),
b=(key:"b"),
c=(key:"c");

a[b]=123;
a[c]=456;

console.log(a[b]);

What's going on? When a new property is set on an object, JavaScript will implicitly do stringify meanings. In the code above, b and c are objects, hence they are both converted to "" (String). Because stringify values ​​are equal, it turns out that we assign a new value the same property.

It is equivalent to writing:

Var a=(),
b="object",
c="object";

a[b]=123;
a[c]=456;

4. Write a simple function to find out if one of the input parameters is equal to 3.

Here the emphasis is on testing knowledge about arguments, but sometimes they go even further and ask to tell how it works Array.prototype.slice.call(arguments).

Function isThreePassed())(
const args = Array.prototype.slice.call(arguments);
return args.indexOf(3) != -1;
) isThreePassed(1,2) //false
isThreePassed(9,3,4,9) //true

As we know, arguments not an array, but a regular object, so it does not have such a useful method as indexOf. For this purpose it is used Array.prototype.slice.call(arguments), which makes of argument - > array.

But still, how does it work?

.call() And. apply() allow you to explicitly set this in function. And if you pass argument like this, That slice will work with it as with a regular array.

Here's an interesting experiment:

Const o = (
"0": "zero",
"1": "one"
);
"0": "zero",
.slice.call(o); // ;
const oo = (
"1": "one",

length: 2

], ] ->

); .slice.call(oo); // ["zero", "one"]; .

5. Combine two nested arrays

The problem can be solved in various ways. Usually they want to find out whether the interviewee knows such a method as reduce .

The idea is to iterate through all the elements of the original array and its “sub-arrays” in order to return the found values ​​to the new array. This happens recursively until we reach the last element.

It also helps us with the formation of a new array

concat

Const flatten = (arr) => arr.reduce((flat, toFlatten) => flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten), );

The correct answer would be: initially, each object has a property - a prototype. You can add methods and properties to it. Create other objects based on the prototype. Created object will automatically inherit the properties of its prototype. If the property is missing in the new object, it will be searched for in the prototype.

Let car = function(model) ( this.model = model; ); car.prototype.getModel = function())( return this.model; ) let honda = new car("honda"); console.log(honda.getModel()); //honda let bmw = new car("bmw"); console.log(bmw.getModel()); //bmw
The car function is called a constructor. Next, we add the getModel method to its prototype using the special construct car.prototype.getModel(). If you do not understand what is being said here, I strongly recommend that you familiarize yourself with the prototypical OOP: https://learn.javascript.ru/prototypes
30% will ask you this or a similar question.

7. Difference between function declaration and function expression?

Function funcA())( console.log("function declaration"); ); var funcB = function() ( console.log("function expression"); )

As you can see, a function expression is a variable to which a function is assigned.
An important feature is that a function declared via function declaration is accessible through the program text before its description. While a function expression behaves like a variable, thus the function can only be accessed after. If we are in the previous example, at the very beginning we add two lines:

Console.log(funcA()); //function declaration concole.log(funcB()); //Uncaught ReferenceError: funcB is not defined.
By the way, instead of var you can use let, with all the ensuing consequences regarding scope.
If you want to pass a function as an argument to another function, then you need to use a function expression. Because it's a variable. That is, pass the variable to another function.

8. What are promises and what are they used for.

Answer this question sometimes difficult, but you can simply say that with the help of them you can perform actions (functions, methods) in an asynchronous manner. You can achieve asynchrony using callbacks, but in the case of large nesting ( large quantity asynchronous actions), we will get poorly readable code.

$.ajax(( url: "test.json", success: function(r) ( $.ajax(( url: "baz.json?" + r.test, success: function(result) ( $("#div1 ").html(result); ) )); ) ));

See how much it branches this code? Now, let's write the same thing using promises (schematically):

Var p1 = new Promise(function(resolve, reject) ( resolve($.ajax("test.json")); )); p1.then(function(r)( return new Promise(...); )).then(function(result)( $(“#div1”).html(result); ));

9. Question about setTimeout()

Most likely, you will not be asked what it is, since the answer to such a question is too obvious. Instead, they will offer a piece of code, and you will have to answer what the result of its execution is.

Console.log("a"); console.log("b"); console.log("c"); //see the sequential output of a then b and c. Now we’ll do the same thing, but we’ll wrap the output “a” in setTimeout().

SetTimeout(function() ( console.log("a"); ), 0);

Logically, since the timeout is 0, we can assume that the output sequence will remain the same. However, in fact, we will see b first, then c, and only at the end – a.
This is because when we use setTimeout, the code that is enclosed in it becomes asynchronous. JS will execute it after the stack is free. That is, after b and c.

10. Closures and how to use them

You will probably be asked a question during an interview.

When one function returns another function (or object), the latter contains the environment of its parent. Let's look at an example:

Let bar = function() ( let i = 0; return ( setI(b) ( i = b; ), getI() ( return i; ) ) ); let x = bar(); x.setI(2); console.log(x.getI()); //2

Finally, I would like to advise you not to rush with answers during the interview, especially to questions related to the analysis of the proposed code. Often questions that are obvious at first glance contain tricks and pitfalls. Stop, think for an extra minute. Ask clarifying questions - this will demonstrate your attentiveness and responsible attitude to the matter. It will help the interviewer to see your train of thought. Actually, this is mainly why tricky or complex tasks. It is much more important to demonstrate correct thinking, even if the answer to the question ends up being wrong.

A person cannot know everything; this is impossible in principle. It often happens that at your previous job you encountered the same technologies and techniques, but at your new job the team has different views on architecture and uses libraries that are not very familiar to you. That is why a competent interviewer will first of all try to find out what kind of person is in front of him, how he thinks, his analytical abilities. In the end, it is very easy to fill in the missing gaps, which cannot be said about the correct thinking of a programmer, which is formed only with experience.