Just to remember the years of failed job interviews and lost hair.

Question 1:console.log(2 + '2')

The answer: ’22’

This is a general interview question. It mainly looks at implicit conversion in JavaScript. In JS + has two main functions: number addition and string concatenation. When both sides of + are not numbers, they will be converted to string concatenation, so the first 2 will be converted to ‘2’ and concatenated with the second ‘2’.

Question 2:console.log(2 - '2')

Answer: 0

– does not operate on strings, but only “subtracts”. When there are non-digits on either side of the string, they are converted to numbers and then subtracted. So the ‘2’ in this case is converted to the number 2, and then 2 minus 2 is 0. NaN results when operands cannot be converted to numbers, such as ‘foo’ -2 = NaN.

*, /, % also behave like -.

Question 3:console.log(true + 1)

Answer: 2

True == 1, false == 0, so true is converted to 1 before addition.

Note: True is equal to 1, false is equal to 0, equal to other numbers is not true, such as true == 2 is false.

Console. log(NaN === NaN)

Answer: false

NaN represents a value Not a number. We just need to remember that NaN is not equal to any value, including itself, whether judged by == or ===! The only way to determine if a value isNaN is with isNaN() or number.isnan ().

Question 5:1.console.log(5 < 6 < 7) 2. console.log(7 > 6 > 5)

(1) True; (2) false

True == 1, false == 0,5 < 6 === true and 1 < 7; 7 > 6 === = true and 1 > 5 === = false, so 2 is false.

Question 6:0.1 + 0.2 =?

Answer: 0.30000000000000004

The problem is not how many zeros there are in the answer, but that it does not equal 0.3! Numbers in Javascript use 64-bit double precision floating-point (see the ECMAScript specification). Just as the decimal system cannot accurately represent 1/3 of the corresponding decimals, there is no way for the binary system to accurately represent 0.1 and 0.2. For example, 0.1 can be converted into binary: 0.0001100110011001100110011001100110011001100110011001101, is an infinite loop, the decimal, and because the computer could not allocate memory to store the infinite number, normally only accurate to much, so the accuracy loss is inevitable, Finally, the calculation results are biased.

Question 7:[1, 2, 3] + [4, 5, 6] =?

Answer: 1,2,34,5,6

Resolution: [1, 2,3].toString() === ‘1,2,3’; Because the final result is ‘1,2,3’ + ‘4,5,6’ === ‘1,2,34,5,6’.

If we want to concatenate arrays we can:

[1.2.3].concat([4.5.6]);

// Or use spread opertator[[...1.2.3], ...[4.5.6]].Copy the code

Problem 8: Print the result

(function () {
  var a = b = 100; }) ();console.log(a);
console.log(b);
Copy the code

Answer: Uncaught ReferenceError: A is not defined

Var a = (b = 100); B = 100. Since there is no local variable b in the function body, a global variable b is defined and 100 is assigned. A = b then assigns the value of b to the local variable A. Console. log(a) was not executed because a was not defined in the global scope. If you put console.log(b) first, you will print 100 and then report an error.

Using strict mode (‘use strict’) avoids the creation of unexpected global variables like B.

Problem 9: Find the print result

for (var i = 0; i < 5; i++) {
  setTimeout(function () {
    console.log(i);
  }, 0);
}
Copy the code

Answer: 5. 5. 5

This is a classic question to examine the understanding of scope and event loop. The scope of a variable defined by var is functional scope, so the above code equals:

var i;

for (i = 0; i < 5; i++) {
  ...
}
Copy the code

Finally, the I in console.log(I) refers to the outside one, and due to the Event loop mechanism, the setTimeout callback is pushed to the Task Queue until the for loop in the Call stack finishes. At this point I has become 5, so the final print will be 5 5’s. With the popularization of ES6, var is used less and less, and let and const become the mainstream. In this case, if you want to print 0, 1, 2, 3, 4, just replace var with let.

Problem 10: Find the print result

function foo() {
  return x;

  function x() {}}console.log(typeof foo());
Copy the code

The answer: ‘function’

C) function promotion d) function promotion There are generally two ways to define a function:

  1. Function declaration:function fn(){ ... }
  2. Function expression:var fn = function(){ ... }

Function declarations which have the function of ascension, but not for function (function expression is variable, but the initialization will not be promoted, so don’t have function of ascension effect), namely the JS compilation phase will elevate the definition of function to scope the top (in fact does not modify the code structure, but in memory for processing). So this code is equivalent to:

function foo() {
  function x() {
    console.log(`hi`);
  }
  
  return x;
}
Copy the code

So, the result prints function. The main purpose of a function promotion is that it can be called before the function is defined.

Problem 11: Find the print result

var x = 1;
function x(){}

console.log(typeof x);
Copy the code

The answer: ‘number’

Variable promotion and function promotion, and their priority. Function promotion takes precedence over variable promotion, so the function is promoted to the top of the scope, followed by variable definition, so this is equivalent to:

function x(){}
var x;
x = 1;

console.log(typeof x);
Copy the code

So x is ultimately a number.

Problem 12: Find the print result

const fn = (a)= > arguments;

console.log(fn("hi"));
Copy the code

Uncaught ReferenceError: Arguments are not defined

C) arrow function d) arrow function The arrow function does not have its own this and arguments; instead, it refers to the outer scope of the argument, and the arguments variable is not defined globally, so an error is reported.

To access the parameter set in the arrow function, Rest parameters are recommended :(… args) => { }

Problem 13: Find the print result

const fn = function () {
  return
  {
    message: "hello"; }};console.log(fn());
Copy the code

Answer: undefined

Resolution:

In JavaScript, if there is a Line Terminator between the return keyword and the return value, the return is automatically followed by a ‘; ‘, see Automatic Semicolon insertion (ASI). So this code is equivalent to:

const fn = function () {
  return;
  {
    message: "hello"; }};console.log(fn());
Copy the code

The result is therefore undefined.

Problem 14: Find the print result

setTimeout((a)= > {
  console.log("a");
}, 1);

setTimeout((a)= > {
  console.log("b");
}, 0);
Copy the code

Answer: it may be ‘a’ ‘b’ or ‘b’ ‘a’ depending on the environment in which js is run.

  • In Node.js, 0ms is equivalent to 1ms, because 0 is converted to 1, so running in Node results in ‘a’ ‘b’.

  • Chrome is similar to Node, and the result is’ A ‘ ‘B’.

  • Firefox will print ‘B’ and ‘A’

The topic belongs to the “back” word how many kinds of writing that kind, and no much practical value 😢.

Question 15:event.target 和 event.currentTargetThe difference between

Answer: Event. target is the element that actually triggers the event, and event.currentTarget is the element that binds the Event Handler.

Such as:

<div id="container">
  <button>click me</button>
</div>
Copy the code
const container = document.getElementById("container");
container.addEventListener("click".function (e) {
  console.log("target =", e.target);
  console.log("currentTarget =", e.currentTarget);
});
Copy the code

Problem 16: Find the print result

function(){
  console.log('hi'); } ()Copy the code

Uncaught SyntaxError: Function statements require a Function name

What is the meaning of IIFE? This code is equivalent to:

function(){
  console.log('hi');
}

()
Copy the code

Function (){function(){… }) ().

Problem 17: Find the print result

const arr = [1.2.3];
arr[- 1] = - 1;
console.log(arr[arr.indexOf(100)]);
Copy the code

Answer: 1

IndexOf () = indexOf(); indexOf(); First, the array is essentially a JavaScript object, so you can set properties. Even if the array index does not have -1, -1 still exists as the key of the object, so x[-1] = -1 is fine. The indexOf() method then returns -1 if the value it looks for does not exist in the array, so it ends up finding console.log(arr[-1]), which returns -1.

18: Find the result of sorting the array

const arr = [5.22.1.14.2.56.132.88.12];
console.log(arr.sort());
Copy the code

Answer: [1, 12, 132, 14, 2, 22, 5, 56, 88]

Resolution:

The array sort() method is used to sort the array. By default, sort() converts elements to strings and compares them to utF-16 encoded sequences of unit values in ascending order. For example, utF-16 codes for 2 and 12 are 50 and 49, respectively, and 49 is less than 50, so 12 comes before 2.

If you want to rank the numbers in ascending order, you pass in a comparison function:

/ / ascending
arr.sort((a, b) = > a - b);
/ / descending
arr.sort((a, b) = > b - a);
Copy the code

Problem 19: FindxThe value of makes the following equations simultaneously betrue

x * x === 0;
x + 1= = =1;
x - 1= = =- 1;
x / x === 1;
Copy the code

Answer: Number. MIN_VALUE

Resolution:

Number.MIN_VALUE is the smallest positive Number that JavaScript can represent and the value closest to 0, so many behaviors are similar to 0, such as the first three equations, but it is not 0 after all, so it can be used as a divisor, so equation 4 is also valid. This is countered by number.max_value, which is the largest Number that can be represented in JavaScript.

20. Console. log(9999999999999999)

Answer: 10000000000000000

Resolution:

The answer is a bit confusing, and my gut tells me that it must have something to do with some of the maximum number limits in JavaScript. MAX_SAFE_INTEGER has a value of 2^ 53-1, 9007199254740991. This number exists because of the 64-bit double precision floating point number used by JS. The range it can represent is only -(2^ 53-1) ~ 2^ 53-1. The number beyond this range is not “safe”, which means that it cannot accurately represent and compare these numbers. MAX_SAFE_INTEGER + 1 === number. MAX_SAFE_INTEGER + 2 The result is true. Number.issafeinteger () can be used to determine whether a Number is “safe”.

BigInt is recommended when we need to use larger numbers.

Question 21: What is the top layer of the prototype chain?

Answer: null

Resolution:

Object. Prototype has an internal attribute called __proto__, and Object.prototype.__proto__ is null. So null is more accurate.

See Annotated ECMAScript 5.1 – Properties of the Object Prototype Object

22. How do I prevent attributes from being set to an object

Such as:

const obj = {};

// todo: void obj.p = 1

obj.p = 1;
Copy the code

Answer: There are at least four ways:

  1. Object.freeze(obj)
  2. Object.seal(obj)
  3. Object.preventExtensions(obj)
  4. Object.defineProperty(obj, 'p', { writable: false })

Resolution:

  1. Object.freeze()At its strictest, it completely forbids the object from making any changes, including adding new properties, modifying existing properties, and modifying its prototype
  2. Object.seal()The rules are a little looser: change is allowedwritableThe new and deleted attributes are not allowed. The existing attributes are marked as non-configurable, and works without any additional control.
  3. Object.preventExtensions()Looser, preventing objects from adding new attributes and modifying them__proto__(can’t give__proto__Reassignment)
  4. Object.defineProperty()The attributepIs defined as unwritable and therefore cannot be given againpSet the new value (writableThe default isfalseCan be omitted.

23. Determine if a string is a palindrome, ignoring case

Basic algorithm, there are at least two ways:

** Solution 1: ** Convert a number to a string, then to an array, then to a comparison:

function palindrome(str) {
  str = str.toLowerCase();
  return str.split("").reverse().join("") === str;
}
Copy the code

** solution 2: **for loop, head to tail comparison

function palindrome(str) {
  for (var i = 0; i < str.length / 2; i++) {
    const left = str[i];
    const right = str[str.length - 1 - i];
    if(left.toLowerCase() ! == right.toLowerCase())return false;
  }

  return true;
}
Copy the code

An updated version of this problem is to determine whether a number is a palindrome and cannot be converted to a string. The idea is to obtain each digit through the method of mod, and then construct an inverse number to compare with the original number:

function palindrome(num) {
  let copy = num;
  let currentDigit = 0;
  let reversedNum = 0;
  do {
    currentDigit = copy % 10;
    reversedNum = reversedNum * 10 + currentDigit;
    copy = parseInt(copy / 10);
  } while(copy ! = =0);

  return num === reversedNum;
}
Copy the code

All right, let’s think about that. If this article helped you, give it a thumbs up!