JavaScript interview questions you need to know

Source: Internet
Author: User
Tags closure numeric logical operators mixed numeric value object object variable scope

Question 1: Scope
Check out the following code:

(Function (){
Var a = B = 5;
})();
Console. log (B); what will be output in the result?

Answer:

5

The main points of this question are two different scopes. 'A' is declared as a local variable by var, but 'B' is not actually defined, so it is a global variable.

Another important issue is strict mode. If you select strict mode, the code above will report Uncaught ReferenceError because B is not defined, it can help you check out some code problems:

(Function (){
'Use strict ';
Var a = window. B = 5;
})();
Console. log (B); Question 2: create the "native" method
Write a method for repeatedly printing string objects. Enter an integer that represents the number of words that are repeatedly printed, for example:

1. console. log ('Hello'. repeatify (3 ));
This will print hellohellohello.
Answer:
One of the implementation methods is as follows:


String. prototype. repeatify = String. prototype. repeatify | function (times ){
Var str = '';
For (var I = 0; I <times; I ++ ){
Str + = this;
    }
Return str;
}. This question examines the developer's knowledge about JavaScript inheritance and prototype attributes.

Question 3: Hoisting
What is the output result of the following code?


Function test (){
Console. log ();
Console. log (foo ());
Var a = 1;
Function foo (){
Return2;
    }
    }

Test (); answer
Undefined and 2.

The above code is equivalent to the following code:


Function test (){
Var;
Function foo (){
Return2;
    }
Console. log ();
Console. log (foo ());
A = 1;
    }
Test (); Question 4: how to execute
The following code provides the result and explains your answer:


Var fullname = 'John Doe ';
Var obj = {
Fullname: 'Colin ihrig ',
Prop :{
Fullname: 'aurelio De Rosa ',
GetFullname: function (){
Returnthis. fullname;
    }
    }
};
Console. log (obj. prop. getFullname ());
Var test = obj. prop. getFullname;
Console. log (test (); answer:
Aurelio De Rosa and John Doe.

Question 5: call () and apply ()
After solving the preceding problem, let the last console. log () output Aurelio De Rosa.

Answer:
The problem lies in call () or apply (). If you do not know the differences between them, I will build you to read first What's the difference between function. call and function. apply? The following code uses call (), but in this case, apply () produces the same result:

Console. log (test. call (obj. prop ));

 

1. UseTypeof bar = "object"JudgmentBarIs an object having potential drawbacks? How can we avoid such disadvantages?
Use TypeofThe 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 use Object. 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 [] = FalseYes False.
2. The following code will output the magic horse in the console? Why?
(Function () {var a = B = 3 ;}) (); console. log ("a defined? "+ (Typeof! = '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); // 3 console, log (typeof a); // undefined
Disassemble the variable assignment in the self-executed function:
B = 3; var a = B;
So BBecomes a global variable, and AIs 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, so FuncIIFE has its own independent scope, and it can access SelfSo the third output will report an error because ThisWithin the accessible scope is UndefinedAnd 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 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 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 case, in order to parse the code correctly, the semicolon will not be automatically filled, but Return, 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 returns Undefined.
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 is NaN:
Console. log (isNaN (NaN); // trueconsole. log (isNaN (23); // falseconsole. log (isNaN ('Ds'); // trueconsole. log (isNaN ('321_sdasd '); // 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.30020.0000000004lele.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 0.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-in ToPrecision ()And ToFixed ()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 set XConvert 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 ^ 53To 2 ^ 53Between (excluding two endpoints). Beyond this range, this value cannot be exactly expressed. ES6 introduced Number. MAX_SAFE_INTEGERAnd Number. MIN_SAFE_INTEGERThese two constants are used to indicate the upper and lower limits of the range and provide 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 CodewarsSome 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. 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.
For Reverse ()The description is of soy sauce:
The code is as follows: Copy code
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); // '123'
  • 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 numberNaN
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 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 is False, 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 is True, 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, common FalseValue:
0, '0', + 0,-0, false, '', null, undefined, null, NaN
Note: Empty array ([])And Empty object ({}):
Console. log ([] = false) // trueconsole. log ({}= = false) // falseconsole. log (Boolean ([]) // trueconsole. log (Boolean ({}) // true
Therefore IfMedium, []And {}Are shown 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. Refer to the explanation in the original article:
The code is as follows: Copy code
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 [Object Object]. As a result, a [B] anda [c] are both equivalent to [ [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 ());
Set GetSecretIdentityAssigned StoleSecretIdentityIs equivalent to defining StoleSecretIdentityFunction:
Var stoleSecretIdentity = function () {return this. _ name ;}
StoleSecretIdentityThe context of is the global environment, so the first output Undefined. To output John Doe Call, ApplyAnd BindAnd other methods StoleSecretIdentityOf ThisPoint to (hero ).
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 }}
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.