search
HomeWeb Front-endJS Tutorial24 JavaScript interview questions

24 JavaScript interview questions

Nov 16, 2017 pm 03:14 PM
javascriptjstest questions

24 JavaScript interview questions

Nowadays, more and more people choose the programmer industry. When we finish our studies, we will go out to find jobs, so some people will inevitably feel very uncomfortable during the interview. Nervous and timid. During a programmer interview, in addition to the interviewer, there are also interview questions specifically designed to assess your ability, so this article is about 24 JavaScript interview questions. Now friends, there is a benefit, so hurry up and get it!

Recommended related articles:The most complete collection of js interview questions in 2020 (latest)

1. There are some potential disadvantages in using typeof bar === "object" to determine whether bar is an object? How to avoid this drawback?

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

It can be seen from the above output that typeof bar === "object" cannot accurately determine that bar is an Object. You can avoid this drawback by 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]

2. Will the following code output something wrong on 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 changed to the following:

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

Disassemble the variable assignment in the self-executing function:

b = 3;var a = b;

So b becomes a global variable, and a is a local variable of the self-executing function.

3. What will the following code output to 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 first and second outputs are not difficult to judge. Before ES6, JavaScript only had function scope, so the IIFE in func had its own independent scope, and it could access the external scope. self in , so the third output will report an error because this is undefined in the accessible scope, and the fourth output is bar. If you know closures, it is 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, you can click here: Talking about closures from the scope chain

4. Include JavaScript code in What does a function block mean? Why do this?

In other words, why use Immediately-Invoked Function Expression?

IIFE has two classic usage scenarios, one is similar to regularly outputting 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 0, 1, 2, 3, 4 as you think, but all the output is 5, then IIFE can be useful:

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

And in JQuery In the development of /Node plug-ins and modules, it is also a big IIFE to avoid variable pollution:

(function($) { 
        //代码
 } )(jQuery);

5. What are the benefits of developing JavaScript in strict mode ('use strict')?

Eliminate some unreasonable and imprecise aspects of Javascript syntax and reduce some weird behaviors;

Eliminate some unsafe aspects of code running and ensure the safety of code running;

Improve compiler efficiency and increase running speed;

Pave the way for new versions of Javascript in the future.

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, semicolons (;) are basically used to separate statements, which can increase the readability and neatness of the code. In JS, if each statement occupies a separate line, you can usually omit the semicolon (;) between statements. The JS parser will decide whether to automatically fill in the semicolon based on whether it can be compiled normally:

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

In the above In this case, in order to correctly parse the code, the semicolon will not be automatically filled in. However, for return, break, continue and other statements, if it is followed by a newline, the parser will automatically fill in the semicolon (;) at the end, so the above The second function becomes like this:

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

So the second function returns undefined.

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

NaN is the abbreviation of Not a Number, a special numerical 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(&#39;ds&#39;)); //trueconsole.log(isNaN(&#39;32131sdasd&#39;));
  //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() 成为了 Number 的静态方法:Number.isNaN().

8. Explain the output of the following code

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

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

Due to the use of binary, JavaScript cannot limitly represent fractions such as 1/10, 1/2, etc. In binary, 1/10 (0.1) is represented as 0.00110011001100110011... Note that 0011 is repeated infinitely, which is caused by rounding errors, so for operations such as 0.1 + 0.2, the operands will first be converted into binary, and then Recalculate:

0.1 => 0.0001 1001 1001 1001… (infinite loop)
0.2 => 0.0011 0011 0011 0011… (infinite loop)

Decimal of double precision floating point number Part supports up to 52 bits, so after adding the two, we get a string of 0.0100110011001100110011001100110011001100... A binary number that is truncated due to the limitation of decimal places in floating point numbers. At this time, convert it to decimal and it becomes 0.30000000000000004.

对于保证浮点数计算的正确性,有两种常见方式。

一是先升幂再降幂:

function add(num1, num2){
  let r1, r2, m;
  r1 = (&#39;&#39;+num1).split(&#39;.&#39;)[1].length;
  r2 = (&#39;&#39;+num2).split(&#39;.&#39;)[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

二是是使用内置的 toPrecision() 和 toFixed() 方法,注意,方法的返回值字符串。

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

9、实现函数 isInteger(x) 来判断 x 是否是整数

可以将 x 转换成10进制,判断和本身是不是相等即可:

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

ES6 对数值进行了扩展,提供了静态方法 isInteger() 来判断参数是否是整数:

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

JavaScript能够准确表示的整数范围在 -2^53 到 2^53 之间(不含两个端点),超过这个范围,无法精确表示这个值。ES6 引入了Number.MAX_SAFE_INTEGER 和 Number.MIN_SAFE_INTEGER这两个常量,用来表示这个范围的上下限,并提供了 Number.isSafeInteger() 来判断整数是否是安全型整数。

10、在下面的代码中,数字 1-4 会以什么顺序输出?为什么会这样输出?

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

这个就不多解释了,主要是 JavaScript 的定时机制和时间循环,不要忘了,JavaScript 是单线程的。

11、写一个少于 80 字符的函数,判断一个字符串是不是回文字符串

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

12、写一个按照下面方式调用都能正常工作的 sum 方法

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

针对这个题,可以判断参数个数来实现:

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

13、下面的代码会输出什么?为什么?

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

会输出什么呢?你运行下就知道了,可能会在你的意料之外。

MDN 上对于 reverse() 的描述是酱紫的:

>DescriptionThe reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.>reverse()

会改变数组本身,并返回原数组的引用。>slice 的用法请参考:slice

14、下面的代码会输出什么?为什么?

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

输出什么,自己去运行吧,需要注意三个点:

多个数字和数字字符串混合运算时,跟操作数的位置有关

console.log(2 + 1 + &#39;3&#39;); / /‘33’console.log(&#39;3&#39; + 2 + 1); //&#39;321&#39;

数字字符串之前存在数字中的正负号(+/-)时,会被转换成数字

console.log(typeof &#39;3&#39;);   // stringconsole.log(typeof +&#39;3&#39;);  //number

同样,可以在数字前添加 '',将数字转为字符串

console.log(typeof 3);   // numberconsole.log(typeof (&#39;&#39;+3));  //string

对于运算结果不能转换成数字的,将返回 NaN

console.log(&#39;a&#39; * &#39;sd&#39;);   //NaNconsole.log(&#39;A&#39; - &#39;B&#39;);  // NaN

这张图是运算转换的规则

24 JavaScript interview questions

15、如果 list 很大,下面的这段递归代码会造成堆栈溢出。如果在不改变递归模式的前提下修善这段代码?

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

原文上的解决方式是加个定时器:

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

解决方式的原理请参考第10题。

16、什么是闭包?举例说明

可以参考此篇:从作用域链谈闭包(去看看)

17、下面的代码会输出什么?为啥?

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

请往前面翻,参考第4题,解决方式已经在上面了

18、解释下列代码的输出

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

逻辑与和逻辑或运算符会返回一个值,并且二者都是短路运算符:

逻辑与返回第一个是 false 的操作数 或者 最后一个是 true的操作数

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

如果某个操作数为 false,则该操作数之后的操作数都不会被计算

逻辑或返回第一个是 true 的操作数 或者 最后一个是 false的操作数

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

如果某个操作数为 true,则该操作数之后的操作数都不会被计算

如果逻辑与和逻辑或作混合运算,则逻辑与的优先级高:

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

在 JavaScript,常见的 false 值:

0, &#39;0&#39;, +0, -0, false, &#39;&#39;,null,undefined,null,NaN

要注意空数组([])和空对象({}):

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

所以在 if 中,[] 和 {} 都表现为 true:

24 JavaScript interview questions

19、解释下面代码的输出

console.log(false == '0')console.log(false === '0')请参考前面第14题运算符转换规则的图。

20、解释下面代码的输出

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

输出是 456,参考原文的解释:

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].

21、解释下面代码的输出

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

结果是10的阶乘。这是一个递归调用,为了简化,我初始化 n=5,则调用链和返回链如下:

24 JavaScript interview questions

22、解释下面代码的输出

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

输出1,闭包能够访问外部作用域的变量或参数。

23、解释下面代码的输出,并修复存在的问题

var hero = {    _name: &#39;John Doe&#39;,    getSecretIdentity: function (){        return this._name;    }};
var stoleSecretIdentity = hero.getSecretIdentity;console.log(stoleSecretIdentity());console.log(hero.getSecretIdentity());
将 getSecretIdentity 赋给 stoleSecretIdentity,等价于定义了 stoleSecretIdentity 函数:
var stoleSecretIdentity =  function (){return this._name;}

stoleSecretIdentity 的上下文是全局环境,所以第一个输出 undefined。若要输出 John Doe,则要通过 call 、apply 和 bind 等方式改变 stoleSecretIdentity 的this 指向(hero)。

第二个是调用对象的方法,输出 John Doe。

24、给你一个 DOM 元素,创建一个能访问该元素所有子元素的函数,并且要将每个子元素传递给指定的回调函数。

函数接受两个参数:

DOM
指定的回调函数

原文利用 深度优先搜索(Depth-First-Search) 给了一个实现:

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

以上就是24个JavaScript的面试题,不管你是不是准备要出去找工作了,我相信这一套题目对大家都很有帮助。

相关推荐:

php初级面试题之简述题(一)

php初级面试题之简述题(二)

关于javascript常见面试题_javascript技巧

最让人容易出错的10道php面试题

php面试题中笔试题目的汇总

The above is the detailed content of 24 JavaScript interview questions. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor