25 JavaScript interview questions you need to know

Source: Internet
Author: User

25 JavaScript interview questions you need to know

1. Usetypeof bar === "object"JudgmentbarIs an object having potential drawbacks? How can we avoid such disadvantages?

UsetypeofThe disadvantage is obvious.instanceof):

let obj = {};let arr = [];console.log(typeof obj === 'object');  //trueconsole.log(typeof arr === 'object');  //trueconsole.log(typeof null === 'object');  //true

According to the output,typeof bar === "object"It cannot be accurately determined.barIs an Object. You can useObject.prototype.toString.call(bar) === "[object Object]"To avoid this drawback:

let obj = {};let arr = [];console.log(Object.prototype.toString.call(obj));  //[object Object]console.log(Object.prototype.toString.call(arr));  //[object Array]console.log(Object.prototype.toString.call(null));  //[object Null]

In addition, keep away from==:

While[] === falseYesfalse.

2. The following code will output the magic horse in the console? Why?

(function(){  var a = b = 3;})();console.log("a defined? " + (typeof a !== 'undefined'));   console.log("b defined? " + (typeof b !== 'undefined'));

This is related to the variable scope. The output is replaced with the following:

console.log(b); //3console,log(typeof a); //undefined

Disassemble the variable assignment in the Self-executed function:

b = 3;var a = b;

SobBecomes a global variable, andaIs a local variable of the Self-executed function.

3. Will the following code output the magic horse on the console? Why?

var myObject = {    foo: "bar",    func: function() {        var self = this;        console.log("outer func:  this.foo = " + this.foo);        console.log("outer func:  self.foo = " + self.foo);        (function() {            console.log("inner func:  this.foo = " + this.foo);            console.log("inner func:  self.foo = " + self.foo);        }());    }};myObject.func();

The output of the first and second is not difficult to judge. Before ES6, JavaScript only has the function scope, sofuncIIFE has its own independent scope, and it can accessselfSo the third output will report an error becausethisWithin the accessible scope isundefinedAnd the fourth output isbar. If you know the closure, it is also easy to solve:

(function(test) {            console.log("inner func:  this.foo = " + test.foo);  //'bar'            console.log("inner func:  self.foo = " + self.foo);}(self));

If you are not familiar with the closure, you can stamp this: Talk about the closure from the scope chain.

4. What does JavaScript code mean when it is included in a function block? Why?

In other words, why do I need to execute the Function Expression Immediately (Immediately-Invoked Function Expression ).

IIFE has two classic application scenarios: one is similar to timed output of data items in a loop, and the other is similar to JQuery/Node plug-in and module development.

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

The above output is not what you think is 0, 1, 2, 3, 4, but all the output is 5. Then IIFE can be used:

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

In JQuery/Node plug-ins and module development, to avoid variable contamination, it is also a big IIFE:

(Function ($) {// code}) (jQuery );

5. What are the advantages of JavaScript development in strict mode?

Eliminate unreasonable and non-rigorous Javascript syntax, and reduce some weird behaviors. Eliminate some Insecure code running to ensure the safety of code running. Improve compiler efficiency and speed; it paves the way for future new versions of Javascript.

6. Are the return values of the following two functions the same? Why?

function foo1(){  return {      bar: "hello"  };}function foo2(){  return  {      bar: "hello"  };}

In programming languages, statements are basically separated by semicolons (;), which increases the readability and purity of the Code. In JS, if each statement occupies an independent line, the semicolon (;) between statements can be omitted. The JS parser determines whether to automatically fill the semicolon based on whether the statement can be compiled properly:

var test = 1 + 2console.log(test);  //3

In the above case, in order to parse the code correctly, the semicolon will not be automatically filled, butreturn,break,continueIf the next line is followed, the parser will automatically fill the semicolon (;), so the second function above will become like this:

function foo2(){  return;  {      bar: "hello"  };}

So the second function returnsundefined.

7. Is Shenma NaN, and its type is Shenma? How to test whether a value is NaN?

NaNIs the abbreviation of Not a Number. a special value of JavaScript, which is of the Number type.isNaN(param)To determine whether a value isNaN:

console.log(isNaN(NaN)); //trueconsole.log(isNaN(23)); //falseconsole.log(isNaN('ds')); //trueconsole.log(isNaN('32131sdasd')); //trueconsole.log(NaN === NaN); //falseconsole.log(NaN === undefined); //falseconsole.log(undefined === undefined); //falseconsole.log(typeof NaN); //numberconsole.log(Object.prototype.toString.call(NaN)); //[object Number]

ES6,isNaN()Become a static method of Number:Number.isNaN().

8. Explain the output of the Code in the lower part of explain.

console.log(0.1 + 0.2);   //0.30000000000000004console.log(0.1 + 0.2 == 0.3);  //false

The number type in JavaScript is float, and the floating point in JavaScript uses the IEEE-754 format, which is a binary notation that can accurately represent scores, such as 1/2, 1/8, 1/1024, each floating point occupies 64 bits. However, the binary floating-point representation does not accurately represent simple numbers like 0.1, and there will be rounding errors.

Because binary is used, JavaScript cannot limit the scores such as 1/10 and 1/2. In binary, 1/10 (0.1) is expressed0.00110011001100110011……Note:0011There are infinite duplicates, which are caused by rounding errors. Therefore, for operations like 0.1 + 0.2, the operands are first converted to binary before being calculated:

0.1 => 0.0001 1001 1001 1001... (Infinite loop) 0.2 => 0.0011 0011 0011 0011... (Infinite loop)

The decimal part of a double-precision floating-point number supports a maximum of 52 digits. Therefore, after the two are added, We can get such a string 0.0100110011001100110011001100110011001100... The number of binary digits truncated due to the decimal scale limit of the floating point number. At this time, convert it to decimal, and then it becomes 0.30000000000000004.

There are two common methods to ensure the correctness of floating point calculation.

First, increase the power first and then lower the power:

function add(num1, num2){  let r1, r2, m;  r1 = (''+num1).split('.')[1].length;  r2 = (''+num2).split('.')[1].length;  m = Math.pow(10,Math.max(r1,r2));  return (num1 * m + num2 * m) / m;}console.log(add(0.1,0.2));   //0.3console.log(add(0.15,0.2256)); //0.3756

Second, use the built-intoPrecision()AndtoFixed()Method,Note: The Return Value string of the method.

function add(x, y) {    return x.toPrecision() + y.toPrecision()}console.log(add(0.1,0.2));  //"0.10.2"

9. Implement FunctionsisInteger(x)To determine whether x is an integer.

You can setxConvert it to a decimal system and determine if it is equal to itself:

function isInteger(x) {     return parseInt(x, 10) === x; }

ES6 extends the numeric value and provides a static method.isInteger()To determine whether the parameter is an integer:

Number.isInteger(25) // trueNumber.isInteger(25.0) // trueNumber.isInteger(25.1) // falseNumber.isInteger("15") // falseNumber.isInteger(true) // false

The integer range that JavaScript can accurately represent is-2^53To2^53Between (excluding two endpoints). Beyond this range, this value cannot be exactly expressed. ES6 introducedNumber.MAX_SAFE_INTEGERAndNumber.MIN_SAFE_INTEGERThese two constants are used to indicate the upper and lower limits of the range and provideNumber.isSafeInteger()To determine whether the integer is a security integer.

10. In the following code, in what order will numbers 1-4 be output? Why is this output?

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

This will not be explained much. It mainly involves the timing mechanism and time loop of JavaScript. Don't forget that JavaScript is single-threaded. For more information, see setTimeout to talk about the JavaScript operating mechanism.

11. Write a function with less than 80 characters to determine whether a string is a return string.

function isPalindrome(str) {    str = str.replace(/\W/g, '').toLowerCase();    return (str == str.split('').reverse().join(''));}

I havecodewarsSome good solutions have been included. You can click here: Palindrome For Your Dome.

12. Write a sum method that can work normally by calling the following method:

console.log(sum(2,3));   // Outputs 5console.log(sum(2)(3));  // Outputs 5

To solve this problem, you can determine the number of parameters:

function sum() {  var fir = arguments[0];  if(arguments.length === 2) {    return arguments[0] + arguments[1]  } else {    return function(sec) {       return fir + sec;    }  }}

13. answer the following questions according to the following code snippet:

for (var i = 0; i < 5; i++) {  var btn = document.createElement('button');  btn.appendChild(document.createTextNode('Button ' + i));  btn.addEventListener('click', function(){ console.log(i); });  document.body.appendChild(btn);}

1. ClickButton 4, What will be output on the console?
2. provide an implementation method that meets expectations

1. Any of the five buttons is output 5.
2. Refer to IIFE.

14. What will the following code output? Why?

var arr1 = "john".split(''); j o h nvar arr2 = arr1.reverse(); n h o jvar arr3 = "jones".split(''); j o n e sarr2.push(arr3);console.log("array 1: length=" + arr1.length + " last=" + arr1.slice(-1));console.log("array 2: length=" + arr2.length + " last=" + arr2.slice(-1));

What will be output? You can see it when you run it. It may be unexpected.

Forreverse()The description is of soy sauce:

Description
The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.

reverse()The array itself is changed and the reference of the original array is returned.

sliceFor more information, see slice.

15. What will the following code output? Why?

console.log(1 +  "2" + "2");console.log(1 +  +"2" + "2");console.log(1 +  -"1" + "2");console.log(+"1" +  "1" + "2");console.log( "A" - "B" + "2");console.log( "A" - "B" + 2);

You can run the output on your own. Note the following three points:

When multiple numbers and numeric strings are mixed, they are related to the locations of the operands.
console.log(2 + 1 + '3'); / /‘33’console.log('3' + 2 + 1); //'321'
When a numeric string contains a plus or minus sign (+/-), it is converted to a number.
console.log(typeof '3');   // stringconsole.log(typeof +'3');  //number

Similarly, you can add''To convert digits into strings.

console.log(typeof 3);   // numberconsole.log(typeof (''+3));  //string
If the calculation result cannot be converted to a number NaN
console.log('a' * 'sd');   //NaNconsole.log('A' - 'B');  // NaN

This figure shows the conversion rules.

16. If the list is large, the following recursive code will cause stack overflow. If the Code does not change the recursive mode? <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Vc3ryb25np1_vcd4ncjxwcmugy2xhc3m9 "brush: java;"> var list = readHugeList();var nextListItem = function() { var item = list.pop(); if (item) { // process the list item... nextListItem(); }};

The solution in the original article is to add a Timer:

var list = readHugeList();var nextListItem = function() { var item = list.pop(); if (item) { // process the list item... setTimeout( nextListItem, 0); }};

For details about the solution, refer to question 10th.

17. What is a closure? Example

For details, refer to this article: about closures from the scope chain.

18. What will the following code output? Why?

for (var i = 0; i < 5; i++) { setTimeout(function() { console.log(i); }, i * 1000 );}

Please refer to question 4th. The solution is already on.

19. Explain the output of the following code

console.log("0 || 1 = "+(0 || 1));console.log("1 || 2 = "+(1 || 2));console.log("0 && 1 = "+(0 && 1));console.log("1 && 2 = "+(1 && 2));

The logical and logical operators return a value, and both are short-circuit operators:

Logic and the first response isfalseOr the last one istrueOperations
console.log(1 && 2 && 0);  //0console.log(1 && 0 && 1);  //0console.log(1 && 2 && 3);  //3

If an operand isfalse, The operands after this operand will not be calculated.

Logic or return the first one istrueOr the last one isfalseOperations
console.log(1 || 2 || 0); //1console.log(0 || 2 || 1); //2console.log(0 || 0 || false); //false

If an operand istrue, The operands after this operand will not be calculated.

If the logic and logic are mixed or used, the logic and priority are higher:

console.log(1 && 2 || 0); //2console.log(0 || 2 && 1); //1console.log(0 && 2 || 1); //1

In JavaScript, commonfalseValue:

0, '0', +0, -0, false, '',null,undefined,null,NaN

Note:Empty array ([])AndEmpty object ({}):

console.log([] == false) //trueconsole.log({} == false) //falseconsole.log(Boolean([])) //trueconsole.log(Boolean({})) //true

ThereforeifMedium,[]And{}Are showntrue:

20. Explain the output of the following code

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

See the diagram of the preceding 14th operator conversion rules.

21. Explain the output of the following code.

var a={},    b={key:'b'},    c={key:'c'};a[b]=123;a[c]=456;console.log(a[b]);

The output is 456. Refer to the explanation in the original article:

The reason for this is as follows: When setting an object property, JavaScript will implicitly stringify the parameter value. in this case, since B and c are both objects, they will both be converted to "[object Object]". as a result, a [B] anda [c] are both equivalent to a ["[object Object]"] and can be used interchangeably. therefore, setting or referencing a [c] is precisely the same as setting or referencing a [B].

22. Explain the output of the following code.

console.log((function f(n){return ((n > 1) ? n * f(n-1) : n)})(10));

The result is a factorial of 10. This is a recursive call. To simplify the process, if I initialize n = 5, the call chain and the return chain are as follows:

23. Explain the output of the following code

(function(x) {    return (function(y) {        console.log(x);    })(2)})(1);

Output 1: The closure can access variables or parameters in the external scope.

24. Explain the output of the following code and fix the existing problems.

var hero = {    _name: 'John Doe',    getSecretIdentity: function (){        return this._name;    }};var stoleSecretIdentity = hero.getSecretIdentity;console.log(stoleSecretIdentity());console.log(hero.getSecretIdentity());

SetgetSecretIdentityAssignedstoleSecretIdentityIs equivalent to definingstoleSecretIdentityFunction:

var stoleSecretIdentity =  function (){        return this._name;}

stoleSecretIdentityThe context of is the global environment, so the first outputundefined. To outputJohn Doecall,applyAndbindAnd other methodsstoleSecretIdentityOfthisPoint to (hero ).

The second is to call the object method and OutputJohn Doe.

25. Give you a DOM element, create a function that can access all the child elements of the element, and pass each child element to the specified callback function.

The function accepts two parameters:

The callback function specified by the DOM.

The original article uses Depth-First-Search to provide an implementation:

function Traverse(p_element,p_callback) {   p_callback(p_element);   var list = p_element.children;   for (var i = 0; i < list.length; i++) {       Traverse(list[i],p_callback);  // recursive call   }}

Reference:

25 Essential JavaScript Interview Questions
Immediate execution of function expressions in JavaScript
Detailed description of the strict Javascript Mode

Statement: the answers to the questions in this article only represent the opinions of the bloggers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.