25 JavaScript interview questions you need to know _ javascript skills

Source: Internet
Author: User
This article mainly shares 25 JavaScript interview questions that we need to know. If you want to pass the interview, refer 1. Use typeof bar === "object" to determine if bar is an object with potential drawbacks? How can we avoid such disadvantages?

The disadvantage of using typeof is obvious (this disadvantage is the same as using instanceof ):

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

According to the preceding output, typeof bar = "object" cannot accurately determine that bar is an Object. You can avoid this problem through Object. prototype. toString. call (bar) = "[object Object:

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, to cherish life, please stay away from =:

[] = False returns false.

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;

Therefore, B becomes a global variable, while a is 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 function scopes. Therefore, IIFE in func has its own independent scopes and can access self in the external scopes, therefore, the third output will report an error, because this is undefined in the accessible scope, and the fourth output is bar. 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 closures, refer to this article:Closure from 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 not rigorous Javascript syntax and reduce some weird behavior;
Eliminate some security issues in code running to ensure the security 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 circumstances, in order to parse the code correctly, the semicolon will not be automatically filled, but for statements such as return, break, and continue, if the next line is followed, the parser will automatically fill the semicolon (;) in the back, so the second function above becomes like this:

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

Therefore, the second function returns undefined.

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

NaN is the abbreviation of Not a Number. It is a special value in JavaScript. Its type is Number. You can use isNaN (param) to determine whether a value is NaN:

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]

In ES6, isNaN () becomes the 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 expressed as 0.00110011001100110011 ...... Note that 0011 is infinitely duplicated, which is caused by rounding errors. Therefore, for an operation like 0.1 + 0.2, the operand is first converted to binary and then 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

The second is to use the built-in toPrecision () and toFixed () methods. Note that the return value of the method is a string.

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

9. Implement the isInteger (x) function to determine whether x is an integer.

You can convert x to a decimal system and determine whether x is equal to itself:

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

ES6 extends the numeric value and provides the 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 between-2 ^ 53 and 2 ^ 53 (excluding two endpoints). Beyond this range, this value cannot be accurately expressed. ES6 introduces the constants Number. MAX_SAFE_INTEGER and Number. MIN_SAFE_INTEGER to indicate the upper and lower limits of the range, and provides Number. 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 have met this question on codewars and have included some good solutions. You can stamp it 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. Click Button 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.

Reverse () changes the array itself and returns a reference to the original array.

For slice usage, 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 ''before the number to convert the number into a string.

console.log(typeof 3); // numberconsole.log(typeof (''+3)); //string

If the calculation result cannot be converted to a number, NaN is returned.

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?

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 return the first operand that is false or the last operand that is true

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

If an operand is false, the operations after the operand are not calculated.

Logic or return the first operand that is true or the last operand that is false

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

If an operand is true, the operations after the operand are not 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, common false values:

0, '0', + 0,-0, false, '', null, undefined, null, NaN
Note that empty arrays ([]) and empty objects ({}):

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

Therefore, in if, both [] and {} are true:

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.

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());

Grant getSecretIdentity to stoleSecretIdentity, which is equivalent to defining the stoleSecretIdentity function:

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

The context of is the global environment, so the first output is undefined. To output John Doe, you need to change this point of stoleSecretIdentity (hero) by calling, apply, bind, and so on ).

The second is to call the object method and output John 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:

  • DOM
  • The specified callback function.

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 }}

The above are the 25 JavaScript Interview Questions shared for you. I hope this will help you in the interview.

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.