10 tricky JavaScript snippets for interviews

Job interviews are not entirely predictable, but we still often see common thorny problems. Let's take a look at 10 of them, which often appear in interviews.

"I am an old programmer who has been engaged in Web front-end development for 6 years. At the beginning of this year, I spent a month sorting out a full set of Web front-end training course (Video + source code + Notes + project practice) which is most suitable for self-study in 2021 Buddy buddy, from the most basic HTML+CSS+JS to mobile HTML5, and various frameworks and new technologies, have been packaged and packaged for every front end partner. This is the front end learning place. Welcome to beginners and advanced partners (all front-end courses are concerned about my WeChat official account: web front end learning circle, and then receive web after receiving the reply.

1. Shallow copy

const user = {
  name: "Shoaib",
  info: {
    father: "Ali",
    age: 26,
    email: "shoaib.mehedi@gmail.com"
  },
};

const copy = { ...user };
copy.info.father = "MD";

console.log("original: ", user.info);
console.log("copy:", copy.info);

output

original: { 
    father: 'MD', 
    age: 26, 
    email: 'shoaib.mehedi@gmail.com' 
}
copy: { 
    father: 'MD', 
    age: 26, 
    email: 'shoaib.mehedi@gmail.com' 
}

Why?

Object. Both assign and propagation operators are shallow copies. This means that we copied the first level object.

The code we used before can be written as object assign:

const user = {
  name: "Shoaib",
  info: {
    father: "Ali",
    age: 26,
    email: "shoaib.mehedi@gmail.com"
  },
};

const copy = Object.assign({}, user);
copy.info.father = "MD";

console.log("original: ", user.info);
console.log("copy:", copy.info);

2. JavaScript hoisting

Predict the output of the following codes:

var name = "shoaib";
var age = 26

var info = function () {
  console.log(name);
  console.log(age);
  var name = 20;
};

info();

output

undefined
26

Why?

The output of the code segment is not shoaib and 20, and the results are undefined and 26, which is caused by hoisting in JavaScript.

Let's convert the above code as follows:

var name = "shoaib";
var age = 26

var info = function () {
  var name;
  console.log(name);
  console.log(age);
  name = 20;
};

info();

3. Value assignment

function assign() {
  var numOne = numTwo = 10;
}

assign();

console.log('numTwo', typeof numTwo === 'undefined');
console.log('numOne', typeof numOne === 'undefined');

output

numTwo false
numOne true

Similarly, we can write:

function assign() {
  var numOne= (numTwo = 10);
}

Why?

The assignment operator has a right to left correlation, which means that it will evaluate from right to left. That's why numTwo assigns it a value of 10 and then assigns it to numOne.

4, JavaScript this

var obj = {
    name: "shoaib",
    func: function() {
        var self = this;
        console.log("outer function:  this.name = " + this.name);
        console.log("outer function:  self.name = " + self.name);
        (function() {
            console.log("inner function:  this.name = " + this.name);
            console.log("inner function:  self.name = " + self.name);
        }());
    }
};
obj.func();

output

outer function:  this.name = shoaib
outer function:  self.name = shoaib
inner function:  this.name = undefined
inner function:  self.name = shoaib

Why?

The external functions this and self refer to obj, so both can access the name correctly. But the internal part is different.

Here, this does not refer to obj. That's why this Name is undefined. However, the reference to local variables, self, is still in scope and has appropriate access rights.

5. JavaScript return

function funcOne() {
  return {
    name: "shoaib",
  };
}

function funcTwo() {
  return;
  {
    name: "shoaib";
  }
}
console.log(funcOne());
console.log(funcTwo());

output

{ 
  name: 'shoaib' 
}
undefined

Why?

Here, funcOne successfully returned the object, but the problem is funcTwo. Take a closer look: funcTwo is followed by a semicolon return. This means that nothing will be returned due to the semicolon.

6. Number epsilon

console.log(0.1 + 0.2);
console.log(0.1 + 0.2 == 0.3);

output

0.30000000000000004
false

Why?

This is complicated. The result may be 0.3 and true, but it may not be. In JavaScript, numbers are processed with floating-point precision, so they may not always produce the expected results.

What is the solution?

JavaScript introduces math. XML for this purpose abs. This will help you compare the absolute difference between two numbers.

function almostEqual(numOne, numTwo) {
  return Math.abs( numOne - numTwo ) < Number.EPSILON;
}
console.log(almostEqual(0.1 + 0.2, 0.3));

7. Timeout and interval

(function() {
    console.log(1); 
    setTimeout(function(){console.log(2)}, 1000); 
    setTimeout(function(){console.log(3)}, 0); 
    console.log(4);
})();

output

1
4
3
2

Why?

  • The first and fourth lines of console output without any delay.

  • Then, on the third line, the time limit appears and the log is executed.

  • Finally, the ten second delay ends and the number 2 is displayed.

8. Inverse array

var arrayOne = "shoaib".split('');
var arrayTwo = arrayOne.reverse();
var arrayThree = "mehedi".split('');
arrayTwo.push(arrayThree);
console.log("arrayOne length=" + arrayOne.length + " value=" + arrayOne.slice(-1));
console.log("arrayTwo length=" + arrayTwo.length + " value=" + arrayTwo.slice(-1));

output

arrayOne length = 7 value = m,e,h,e,d,i 
arrayTwo length = 7 value = m,e,h,e,d,i

Why?

  • When reverse is used in JavaScript, this method will not only return the reversed array. It also reverses the order of the array itself.

  • The reverse method returns a reference to the array itself.

For better understanding, here is an example:

const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// expected output: "array1:" Array ["three", "two", "one"]

9. Strict equality

console.log(false == '0') 
console.log(false === '0')

output

true 
false

Why?

In JavaScript, = = compares two things, which is not strict. If you want a strict comparison, you can use = = = instead of = = for comparison, which compares two things and their data types. Again= And== Operators work the same way.

10. JavaScript object

var person = {
    name: 'shoaib',
    identity: function (){
        return this.name;
    }
};

var personCopy = person.identity;

console.log(personCopy());
console.log(person.identity());

output

undefined
shoaib

Why?

The first console is undefined because the method is extracted from the person object, so the identity function is called in the global context without the name attribute.

conclusion

In this article, I try to cover some difficult questions that programmers should understand in order to do better in the interview. I will try to include more content in the future. If I missed anything interesting, please comment below.

Keywords: Javascript Interview

Added by robotta1530 on Fri, 07 Jan 2022 04:13:30 +0200