search
HomeWeb Front-endJS Tutorial7 JavaScript interview questions to get rid of the fake and keep the real

7 JavaScript interview questions to get rid of the fake and keep the real

The following 7 JavaScript interview questions you should ask before the interview. Otherwise, your time will most likely be wasted.
1. What are the two ways to create JavaScript objects?
This is a very simple question if you have ever used JavaScript. You have to know at least one way. But, despite that, in my experience, there are also a lot of people who claim to be JavaScript programmers who say they don't know how to answer this question.

  • Use the "new" keyword to call the function.

  • open/close curly braces.

var o = {};
You can also continue to ask, "When does the new keyword create an object?" However, since I just want to eliminate some people, So I will wait until the actual interview to ask these questions.

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

2. How to create an array ?
This is the same level of question as "how to create an object". However, there are also some people who can answer the first question but cannot answer this question.
Use the following code to create an array simply:
var myArray = new Array();
Creating an array is a very complicated process. But I would like to hear answers from candidates using square brackets.
var myArray = [];
Of course, we can continue to ask other questions, such as how to efficiently remove duplicate elements in JavaScript arrays, etc., but since we only need to know whether the candidate is worthy of further observation, about I will end the question of arrays here.

Let’s talk about how to efficiently delete duplicate elements in JavaScript arrays: 5 methods on how to implement array deduplication in js.

Specific method introduction:
1). Array traversal method
The simplest method to remove duplicates. Implementation idea: Create a new array, traverse the incoming array, and add the value if it is not in the new array. In the new array; Note: The method "indexOf" to determine whether the value is in the array is an ECMAScript5 method. It is not supported below IE8. You need to write more code that is compatible with lower version browsers. The source code is as follows:

// 最简单数组去重法
function unique1(array){
 var n = []; //一个新的临时数组
 //遍历当前数组
 for(var i = 0; i < array.length; i++){
  //如果当前数组的第i已经保存进了临时数组,那么跳过,
  //否则把当前项push到临时数组里面
  if (n.indexOf(array[i]) == -1) n.push(array[i]);
 }
 return n;
}
// 判断浏览器是否支持indexOf ,indexOf 为ecmaScript5新方法 IE8以下(包括IE8, IE8只支持部分ecma5)不支持
if (!Array.prototype.indexOf){
 // 新增indexOf方法
 Array.prototype.indexOf = function(item){
  var result = -1, a_item = null;
  if (this.length == 0){
   return result;
  }
  for(var i = 0, len = this.length; i < len; i++){
   a_item = this[i];
   if (a_item === item){
    result = i;
    break;
   }
  }
  return result;
 }
}

2). Object key-value pairing method
This method executes faster than any other method, but it takes up more memory; implementation idea: create a new js object and a new array, and when traversing the incoming array, judge Whether the value is the key of the js object, if not, add the key to the object and put it into a new array. Note: When determining whether it is a js object key, "toString()" will be automatically executed on the incoming key. Different keys may be mistaken for the same; for example: a[1], a["1"]. To solve the above problem, you still have to call "indexOf".

// 速度最快, 占空间最多(空间换时间)
function unique2(array){
 var n = {}, r = [], len = array.length, val, type;
  for (var i = 0; i < array.length; i++) {
    val = array[i];
    type = typeof val;
    if (!n[val]) {
      n[val] = [type];
      r.push(val);
    } else if (n[val].indexOf(type) < 0) {
      n[val].push(type);
      r.push(val);
    }
  }
  return r;
}

3). The array index judgment method
still has to call "indexOf". The performance is similar to method 1. The implementation idea: if the i-th item of the current array is in the current array If the position that appears once is not i, it means that the i-th item is repeated and is ignored. Otherwise, store the result array.

function unique3(array){
 var n = [array[0]]; //结果数组
 //从第二项开始遍历
 for(var i = 1; i < array.length; i++) {
  //如果当前数组的第i项在当前数组中第一次出现的位置不是i,
  //那么表示第i项是重复的,忽略掉。否则存入结果数组
  if (array.indexOf(array[i]) == i) n.push(array[i]);
 }
 return n;
}

4). Adjacent removal method after sorting
Although the sorting results of the "sort" method of native arrays are not very reliable, there is no disadvantage in deduplication that does not pay attention to order. No impact. Implementation idea: Sort the incoming array so that the same values ​​are adjacent after sorting, and then when traversing, only add values ​​that are not duplicates of the previous value to the new array.

// 将相同的值相邻,然后遍历去除重复值
function unique4(array){
 array.sort();
 var re=[array[0]];
 for(var i = 1; i < array.length; i++){
  if( array[i] !== re[re.length-1])
  {
   re.push(array[i]);
  }
 }
 return re;
}

5). Optimizing array traversal method
comes from foreign blog posts. The implementation code of this method is quite cool; implementation idea: get the rightmost value without duplication and put it into a new array. (When duplicate values ​​are detected, the current loop is terminated and the next round of judgment of the top-level loop is entered)

// 思路:获取没重复的最右一值放入新数组
function unique5(array){
 var r = [];
 for(var i = 0, l = array.length; i < l; i++) {
  for(var j = i + 1; j < l; j++)
   if (array[i] === array[j]) j = ++i;
  r.push(array[i]);
 }
 return r;
}

3. What is Variable Hoisting?
This question is a little more difficult, and I don’t require the other party to answer it. However, this question can quickly determine a candidate’s technical proficiency: Do they really understand the programming language as well as they claim to?
Variable promotion means that no matter where a variable is declared in a scope, the JavaScript engine will move this declaration to the top of the scope. If you declare a variable in the middle of a function, such as assigning a variable in a certain line:

function foo()
{
 // 此处省略若干代码
 var a = "abc";
}

, the code will actually run like this:

function foo()
{
 var a;
 // 此处省略若干代码
 a = "abc";
}

4. What are the risks of global variables, and how can I protect my code from interference?
The danger with global variables is that someone else can create a variable with the same name and then overwrite the variable you are using. This is a headache in any language.
There are many ways to prevent it. The most common method is to create a global variable that contains all other variables:
var applicationName = {};
Then, whenever you need to create a global variable, just attach it to the object.
applicationName.myVariable = "abc";
Another method is to encapsulate all the code into an automatically executed function, so that all declared variables are declared within the scope of the function.

(function(){
 var a = "abc";
})();

在现实中,这两种方法你可能都会用到。
5.如何通过JavaScript对象中的成员变量迭代?

for(var prop in obj){
 // bonus points for hasOwnProperty
 if(obj.hasOwnProperty(prop)){
  // do something here
 }
}

6.什么是闭包(Closure)?
闭包允许一个函数定义在另一个外部函数的作用域内,即便作用域内的其他东西都消失了,它仍可以访问该外部函数内的变量。如果应聘者能够说明,在for/next循环中使用闭包却不声明变量来保存迭代变量当前值的一些风险,那就应该给对方加分。
7.请描述你经历过的JavaScript单元测试。
关于这个问题,其实我们只是想看看应聘人员是否真的做过JavaScript单元测试。这是一个开放式问题,没有特定的正确答案,不过对方至少得能讲述进程中的一些事情。

相关学习推荐:javascript视频教程

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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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 Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment