10 interview questions to improve your JavaScript skills

Writing questions is a good way for us to improve our skills. The following questions are very challenging and "instructive." If you know how to answer, it means that you are at a good level, but if you find that you have answered wrong and can figure out why it is wrong, I think that would be better!

  1. Array sorting comparison
    Looking at the following array, what will be output after various sorting operations?
1const arr1 = ['a', 'b', 'c'];
2const arr2 = ['b', 'c', 'a'];
3
4console.log(
5  arr1.sort() === arr1,
6  arr2.sort() == arr2,
7  arr1.sort() === arr2.sort()
8);

Answer and analysis
Answer: true, true, false

There are several concepts at work here. First, the sort method of array sorts the original array and returns a reference to the array. This means that when you call arr2.sort(), the objects in the arr2 array will be sorted.

When you compare objects, the sort order of the array is not important. Since arr1.sort() and arr1 point to the same object in memory, the first equality test returns true. The second comparison is the same: arr2.sort() and arr2 point to the same object in memory.

In the third test, the sort order of arr1.sort() and arr2.sort() is the same; however, they point to different objects in memory. Therefore, the evaluation result of the third test is false.

  1. set of objects
    to objects below Set turn into a new array, what the final output?
1const mySet = new Set([{ a: 1 }, { a: 1 }]);
2const result = [...mySet];
3console.log(result);

Answer and analysis
Answer: [{a: 1}, {a: 1}]

Although the Set object does delete duplicates, the two values ​​we create with Set are references to different objects in memory, even though they have the same key-value pair. This is the same reason that the result of {a: 1} === {a: 1} is false.

If the set is created with object variables, such as obj = {a: 1}, new Set([obj,obj]) will have only one element, because both elements in the array refer to the same object in memory.

  1. Mutability of Deep Objects The objects
    below represent user Joe and his dog Buttercup. We save the object with Object.freeze, and then try to change the name of Buttercup. What will be output in the end?
 1const user = {
 2  name: 'Joe',
 3  age: 25,
 4  pet: {
 5    type: 'dog',
 6    name: 'Buttercup',
 7  },
 8};
 9
10Object.freeze(user);
11
12user.pet.name = 'Daffodil';
13
14console.log(user.pet.name);

Answer and analysis
Answer: Daffodil

Object.freeze will make the object shallowly freeze, but will not protect the deep properties from being modified. In this example, user.age cannot be modified, but user.pet.name can be modified without problems. If we feel that we need to protect an object from "from beginning to end", we can recursively apply Object.freeze or use the existing "deep freeze" library.

  1. Prototype inheritance
    In the code below, there is a Dog constructor. Our dog obviously has the speak operation. What will be output when we call Pogo's speak?
 1function Dog(name) {
 2  this.name = name;
 3  this.speak = function() {
 4    return 'woof';
 5  };
 6}
 7
 8const dog = new Dog('Pogo');
 9
10Dog.prototype.speak = function() {
11  return 'arf';
12};
13
14console.log(dog.speak());

Answer and analysis
Answer:
Every time woof creates a new Dog instance, we will set the instance's speak property to a function that returns the string woof. Since we have to set this value every time we create a new Dog instance, the interpreter will not find the speak attribute along the prototype chain. As a result, the speak method on Dog.prototype.speak will not be used.

  1. The resolution order of Promise.all
    In this problem, we have a timer function that returns a Promise, which is resolved after a random time. We use Promise.all to resolve a series of timers. What is the final output, is it random?
 1const timer = a => {
 2  return new Promise(res =>
 3    setTimeout(() => {
 4      res(a);
 5    }, Math.random() * 100)
 6  );
 7};
 8
 9const all = Promise.all([timer('first'), timer('second')]).then(data =>
10  console.log(data)
11);

Answer and analysis
Answer: ["first", "second"]

The order of Promise resolution has nothing to do with Promise.all. We can reliably rely on them being returned in the same order provided in the array parameters.

Question 6: Reduce Math
6. Reduce Math
Math time! What is output?

1const arr = [x => x * 1, x => x * 2, x => x * 3, x => x * 4];
2
3console.log(arr.reduce((agg, el) => agg + el(agg), 1));

Answer and Explanation
Answer and analysis
Answer: 120
When using Array#reduce, the initial value of the aggregator (here called agg) is given in the second parameter. In this case, the value is 1. The function can then be iterated as follows:

1 + 1 * 1 = 2 (the value of the aggregator in the next iteration)

2 + 2 * 2 = 6 (the value of the aggregator in the next iteration)

6 + 6 * 3 = 24 (the value of the aggregator in the next iteration)

24 + 24 * 4 = 120 (final value)

So it is 120.

Question 7: Short-Circuit Notification(s)
7. Short-Circuit Notification(s)
Let us show some notifications to the user. What does the following code snippet output?

1const notifications = 1;
2
3console.log(
4  `You have ${notifications} notification${notifications !== 1 && 's'}`

5);
Answer and analysis
Answer: "You have 1 notificationfalse"

Unfortunately, our short-circuit evaluation will not work as expected: notifications !== 1 &&'s' is evaluated as false, which means that we will actually output You have 1 notificationfalse. If you want the code snippet to work properly, you can consider the conditional operator: ${notifications === 1?'':'s'}.

  1. Expand operation and rename
    Look at the array of single objects in the following code. What happens when we expand the array and change the firstname property on the 0 index object?
1const arr1 = [{ firstName: 'James' }];
2const arr2 = [...arr1];
3arr2[0].firstName = 'Jonah';
4
5console.log(arr1);

Answer and analysis
Answer: [{ firstName: “Jonah” }]

The spread operator creates a shallow copy of the array, which means that the object contained in arr2 is the same as the object pointed to by arr1. So modifying the firstName property of an object in one array will also change it in another array.

  1. Array method binding
    What will be output in the following situations?
1const map = ['a', 'b', 'c'].map.bind([1, 2, 3]);
2map(el => console.log(el));

Answer and analysis
Answer: 1 2 3

When ['a','b','c'].map is called, Array.prototype.map with this' value of'['a','b','c'] will be called. But when used as a reference, Array.prototype.map is a reference.

Function.prototype.bind binds the this of the function to the first parameter ([1, 2, 3] in this example). Calling Array.prototype.map with this will cause these items to be iterated and output.

  1. The uniqueness and order of sets
    In the following code, we create a new array with set objects and extended syntax. What will be output in the end?
1const arr = [...new Set([3, 1, 2, 3, 4])];
2console.log(arr.length, arr[2]);

Answer and analysis
Answer: 4 2

The set object will force the elements in it to be unique (the duplicate elements that already exist in the set will be ignored), but the order will not be changed. So the content of the arr array is [3,1,2,4], arr.length is 4, and arr[2] (the third element of the array) is 2.


Finally, give everyone a free wave of benefits

This interview experience, I hope it will help you, prepare well, calm your mind, and usually have useful skills, the interview is not difficult!


Guess you like

Origin blog.csdn.net/CHENXI_0/article/details/106668703