50 JavaScript interview questions with answers

Here are 50 JavaScript interview questions with answers

1. What is the difference between var, let, and const in JavaScript?

English: var has function scope and is hoisted, meaning it can be used before its declaration but can lead to bugs. let and const have block scope. let allows reassignment, while const does not allow reassignment once the variable is initialized.

Chinese: var具有函数作用域并被提升,这意味着可以在声明之前使用,但可能导致错误。letconst具有块作用域。let允许重新赋值,而const一旦变量初始化后就不允许重新赋值。


2. What is the difference between undefined and null?

English: undefined means a variable has been declared but has not been assigned a value. null is an assignment value that represents no value or an empty object pointer. They are different types: undefined is of type undefined, and null is of type object.

Chinese: undefined表示变量已声明但尚未分配值。null是一个赋值,表示没有值或空对象指针。它们是不同的类型:undefined的类型是undefinednull的类型是object


3. What is a closure in JavaScript, and how does it work?

English: A closure is a function that has access to its own scope, the scope of the outer function, and the global scope. Closures allow for data encapsulation and function state persistence by capturing variables from their lexical environment.

Chinese: 闭包是一个具有访问自身作用域、外部函数作用域和全局作用域的函数。闭包通过捕获其词法环境中的变量,实现数据封装和函数状态持久化。


4. Explain event delegation in JavaScript.

English: Event delegation is a technique where a single event listener is added to a parent element, and events triggered by child elements are captured and handled by the parent. This improves performance by reducing the number of event listeners in a document.

Chinese: 事件委托是一种技术,通过在父元素上添加一个事件监听器,捕获并处理由子元素触发的事件。这通过减少文档中的事件监听器数量来提高性能。


5. How does the this keyword work in JavaScript?

English: The value of this in JavaScript depends on how a function is called. In a method, this refers to the object. In a regular function or globally, this refers to the global object (or undefined in strict mode). It can also be explicitly set using bind(), call(), or apply().

Chinese: JavaScript中this的值取决于函数的调用方式。在方法中,this指的是对象。在常规函数或全局中,this指的是全局对象(严格模式下为undefined)。还可以通过bind()call()apply()显式设置this


6. What are JavaScript promises, and how do they work?

English: A promise is an object representing the eventual completion or failure of an asynchronous operation. Promises have three states: pending, fulfilled, or rejected. You can handle promise results using .then(), .catch(), and .finally() methods.

Chinese: Promise是表示异步操作最终完成或失败的对象。Promise具有三种状态:pending(进行中)、fulfilled(已完成)或rejected(已拒绝)。可以使用.then().catch().finally()方法处理Promise的结果。


7. What is the difference between == and === in JavaScript?

English: == checks for equality with type coercion, meaning it converts the operands to the same type before comparing. === checks for strict equality, meaning both the type and value must be the same.

Chinese: ==在比较前进行类型转换,即将操作数转换为相同类型再进行比较。===检查严格相等,意味着类型和值都必须相同。


8. Explain the call(), apply(), and bind() methods.

English: call() and apply() both invoke a function with a specific this context. The difference is that call() accepts arguments individually, while apply() accepts them as an array. bind() creates a new function that, when called, has its this context permanently set to the provided value.

Chinese: call()apply()都用特定的this上下文调用函数。不同的是call()单独接受参数,而apply()接受参数数组。bind()创建一个新函数,当调用时,其this上下文永久设置为提供的值。


9. What is hoisting in JavaScript?

English: Hoisting is JavaScript’s default behavior of moving declarations to the top of the current scope. Variables declared with var are hoisted and initialized as undefined, while let and const declarations are hoisted but not initialized, resulting in a ReferenceError if accessed before initialization.

Chinese: 提升是JavaScript默认将声明移动到当前作用域顶部的行为。使用var声明的变量会被提升并初始化为undefined,而letconst声明的变量会被提升但不初始化,如果在初始化前访问会导致ReferenceError


10. What is the difference between synchronous and asynchronous code?

English: Synchronous code executes sequentially, where each statement waits for the previous one to complete before executing. Asynchronous code does not wait; it allows multiple operations to happen at the same time, typically using callbacks, promises, or async/await.

Chinese: 同步代码按顺序执行,每条语句等待前一条语句完成后再执行。异步代码不会等待,它允许多个操作同时进行,通常使用回调函数、Promise或async/await


11. How does JavaScript’s event loop work?

English: The event loop in JavaScript continuously checks the message queue and the call stack. If the call stack is empty, it dequeues tasks from the message queue (e.g., callbacks) and pushes them to the call stack, allowing asynchronous code execution without blocking the main thread.

Chinese: JavaScript中的事件循环持续检查消息队列和调用栈。如果调用栈为空,它会将任务从消息队列中取出(例如回调函数)并推入调用栈,从而允许异步代码执行而不阻塞主线程。


12. What are arrow functions, and how do they differ from regular functions?

English: Arrow functions are a concise syntax for writing functions in JavaScript. They do not have their own this, arguments, or super, and they cannot be used as constructors. Arrow functions automatically bind this from their surrounding lexical scope.

Chinese: 箭头函数是JavaScript中编写函数的简洁语法。它们没有自己的thisargumentssuper,且不能作为构造函数使用。箭头函数会自动从其周围的词法作用域绑定this


13. What is the difference between forEach() and map() in JavaScript?

English: forEach() iterates over an array, executing a provided function once for each element, without returning a new array. map() also iterates over an array but returns a new array with the results of applying the provided function to each element.

Chinese: forEach()遍历数组,对每个元素执行一次提供的函数,不返回新数组。map()也遍历数组,但返回一个新数组,其中包含对每个元素应用提供的函数后的结果。


14. How does JavaScript handle primitive vs. reference types?

English: Primitive types (e.g., number, string, boolean) are stored by value, meaning each variable holds its own copy of the data. Reference types (e.g., object, array, function) are stored by reference, meaning variables store a reference to the same memory location.

Chinese: 原始类型(例如numberstringboolean)按值存储,这意味着每个变量持有自己的一份数据副本。引用类型(例如objectarrayfunction)按引用存储,这意味着变量存储对相同内存位置的引用。


15. What is debouncing, and how is it implemented in JavaScript?

English: Debouncing is a technique to limit the rate at which a function is executed. It ensures that a function is only called once after a certain period of inactivity. This is commonly implemented using setTimeout to delay execution until the event has stopped occurring for a set amount of time.

Chinese: 防抖是一种限制函数执行频率的技术。它确保在一段时间不活动后,函数只被调用一次。通常使用setTimeout实现,将执行延迟到事件在设定时间内停止发生。


16. What is throttling in

JavaScript, and how is it different from debouncing?
English: Throttling ensures that a function is only called at most once during a specified time period, regardless of how many times the event is triggered. Debouncing delays the function call until a period of inactivity. Throttling is used when you want to ensure a constant execution rate, whereas debouncing is used to wait until an action stops.

Chinese: 节流确保在指定时间段内,函数最多只被调用一次,无论事件触发多少次。防抖则在一段不活动期后才调用函数。节流用于确保恒定的执行率,而防抖用于等待操作停止后再执行。


17. What is the purpose of strict mode in JavaScript?

English: strict mode is a feature that enforces stricter parsing and error handling in JavaScript. It helps catch common coding errors, such as assigning values to undeclared variables, and prevents the use of certain problematic features, making code safer and more optimized.

Chinese: strict mode是一种在JavaScript中强制更严格解析和错误处理的特性。它有助于捕获常见的编码错误,如将值分配给未声明的变量,并防止使用某些有问题的功能,使代码更安全且更优化。


18. What are modules in JavaScript, and how are they implemented?

English: Modules in JavaScript are reusable pieces of code that can be imported and exported between different files. ES6 introduced import and export statements for modules, allowing developers to encapsulate functionality and promote modular design.

Chinese: JavaScript中的模块是可在不同文件之间导入和导出的可重用代码片段。ES6引入了importexport语句用于模块,使开发者能够封装功能并促进模块化设计。


19. How does JavaScript handle asynchronous code execution?

English: JavaScript handles asynchronous code execution using callbacks, promises, and async/await. The event loop coordinates these asynchronous tasks by dequeuing them from the message queue and executing them in the call stack when the stack is empty.

Chinese: JavaScript使用回调函数、Promise和async/await处理异步代码执行。事件循环通过从消息队列中取出异步任务,并在调用栈为空时执行它们,来协调这些任务的执行。


20. What are the differences between setTimeout() and setInterval()?

English: setTimeout() schedules a function to be executed once after a specified delay, while setInterval() schedules a function to be executed repeatedly at fixed intervals. setInterval() continues to execute until cleared with clearInterval(), and setTimeout() is cleared with clearTimeout().

Chinese: setTimeout()在指定延迟后调度函数执行一次,而setInterval()以固定间隔重复调度函数执行。setInterval()持续执行直到被clearInterval()清除,而setTimeout()clearTimeout()清除。


21. What is the difference between document.querySelector() and document.getElementById()?

English: document.querySelector() returns the first element that matches a CSS selector, while document.getElementById() returns the element with a specific ID. querySelector() is more flexible but may be slower because it processes complex CSS selectors.

Chinese: document.querySelector()返回与CSS选择器匹配的第一个元素,而document.getElementById()返回具有特定ID的元素。querySelector()更灵活,但可能较慢,因为它需要处理复杂的CSS选择器。


22. What is the difference between localStorage and sessionStorage?

English: localStorage persists data across browser sessions until it is explicitly deleted, while sessionStorage only persists data for the duration of the page session (i.e., until the browser tab is closed). Both store data as key-value pairs and have the same API.

Chinese: localStorage在浏览器会话之间持久化数据,直到显式删除,而sessionStorage仅在页面会话期间持久化数据(即,直到浏览器标签关闭)。两者都将数据存储为键值对,并具有相同的API。


23. Explain the concept of hoisting in JavaScript.

English: Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their containing scope before execution. However, only declarations are hoisted, not initializations, so accessing a variable before its initialization results in undefined.

Chinese: 提升是JavaScript的一种机制,在执行之前,变量和函数声明会被提升到其包含作用域的顶部。然而,只有声明被提升,初始化不会被提升,因此在初始化前访问变量会返回undefined


24. What is the this keyword in JavaScript, and how is it determined?

English: The value of this is determined by how a function is called. In a method, this refers to the object that owns the method. In a constructor, it refers to the new object being created. If not in a method or constructor, this refers to the global object in non-strict mode or undefined in strict mode.

Chinese: this关键字的值取决于函数的调用方式。在方法中,this指的是拥有该方法的对象。在构造函数中,this指的是正在创建的新对象。如果不在方法或构造函数中,this在非严格模式下指的是全局对象,在严格模式下指的是undefined


25. What is JSON, and how do you work with it in JavaScript?

English: JSON (JavaScript Object Notation) is a lightweight data-interchange format. In JavaScript, you can parse a JSON string into an object using JSON.parse() and convert an object into a JSON string using JSON.stringify().

Chinese: JSON(JavaScript对象表示法)是一种轻量级的数据交换格式。在JavaScript中,您可以使用JSON.parse()将JSON字符串解析为对象,并使用JSON.stringify()将对象转换为JSON字符串。


26. What is memoization, and how can it be implemented in JavaScript?

English: Memoization is an optimization technique where results of expensive function calls are cached based on the input arguments. In JavaScript, it can be implemented using a closure that stores results in an object, returning cached results for repeated inputs.

Chinese: 记忆化是一种优化技术,通过根据输入参数缓存耗时函数调用的结果。在JavaScript中,可以使用闭包实现,它将结果存储在对象中,并在遇到重复输入时返回缓存结果。


27. How do JavaScript’s prototypes work?

English: Every JavaScript object has a prototype, which is another object from which it inherits properties and methods. This is known as prototype-based inheritance, allowing objects to share behavior without the need for classical inheritance.

Chinese: 每个JavaScript对象都有一个prototype,它是另一个对象,允许对象继承属性和方法。这被称为原型继承,允许对象共享行为,而不需要传统的继承机制。


28. What is the difference between apply(), call(), and bind() methods?

English: apply() and call() invoke a function with a specific this context and arguments. The difference is that call() accepts arguments individually, whereas apply() accepts them as an array. bind() creates a new function with a bound this, but does not execute it immediately.

Chinese: apply()call()使用特定的this上下文和参数调用函数。不同之处在于call()单独接受参数,而apply()接受参数数组。bind()创建一个绑定了this的新函数,但不会立即执行。


29. Explain currying in JavaScript.

English: Currying is a technique where a function with multiple arguments is transformed into a sequence of functions, each taking one argument. This allows for partial function application, where some arguments are fixed in advance, and the remaining arguments are passed later.

Chinese: 柯里化是一种将具有多个参数的函数转换为一系列函数的方法,每个函数只接受一个参数。这允许部分应用函数,其中某些参数可以预先固定,剩余的参数可以稍后传递。


30. What is the difference between undefined and null in JavaScript?

English: undefined means a variable has been declared but has not yet been assigned a value. null is an assignment value that represents "no value" or "empty value". They are different types: undefined is of type undefined, while null is of type object.

Chinese: undefined表示变量已经声明但尚未赋值。null是一种赋值,表示“没有值”或“空值”。它们是不同的类型:undefined的类型是undefined,而null的类型是object


31. What is event delegation in JavaScript?

English: Event delegation is a pattern where a single event listener is attached to a parent element to manage events from multiple child elements. The event is "delegated" to the parent element and uses

event bubbling to handle the events from the children.

Chinese: 事件委托是一种模式,通过将一个事件监听器附加到父元素来管理多个子元素的事件。事件被“委托”给父元素,并使用事件冒泡处理来自子元素的事件。


32. What is the prototype chain in JavaScript?

English: The prototype chain is a series of linked objects that JavaScript uses for inheritance. When trying to access a property on an object, JavaScript looks for it on the object itself and continues up the chain through the object’s prototype until it reaches null or finds the property.

Chinese: 原型链是JavaScript用于继承的一系列链接对象。当尝试访问对象上的属性时,JavaScript会在对象本身上查找,并沿着对象的原型链继续向上查找,直到找到该属性或到达null


33. What is a promise in JavaScript?

English: A promise is an object that represents the eventual completion (or failure) of an asynchronous operation. It has three states: pending, fulfilled, and rejected. It is used to handle asynchronous operations in a more readable way using .then(), .catch(), and .finally().

Chinese: Promise是一个对象,表示异步操作最终完成(或失败)。它具有三种状态:pending(进行中)、fulfilled(已完成)和rejected(已拒绝)。它用于以更易读的方式处理异步操作,使用.then().catch().finally()


34. How does hoisting work in JavaScript?

English: Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their scope before code execution. However, while declarations are hoisted, variable initializations are not, leading to potential undefined values if accessed before initialization.

Chinese: 提升是JavaScript中的一种行为,变量和函数声明在代码执行前会被提升到其作用域的顶部。然而,虽然声明会被提升,但变量的初始化不会被提升,如果在初始化前访问,可能会返回undefined值。


35. What is the difference between slice() and splice() in JavaScript?

English: slice() returns a shallow copy of a portion of an array without modifying the original array. splice() modifies the array in place by adding, removing, or replacing elements. slice() is non-destructive, while splice() alters the original array.

Chinese: slice()返回数组的一部分的浅拷贝,不会修改原始数组。splice()通过添加、删除或替换元素直接修改数组。slice()是非破坏性的,而splice()会改变原始数组。


36. How do JavaScript promises differ from callbacks?

English: Promises provide a more structured way of handling asynchronous operations compared to callbacks. Promises avoid "callback hell" by chaining with .then() and .catch(). They also improve error handling, while callbacks require nested error checks.

Chinese: Promise比回调函数提供了更结构化的处理异步操作的方式。Promise通过.then().catch()进行链式调用,避免了“回调地狱”。Promise还改善了错误处理,而回调函数则需要嵌套的错误检查。


37. What is use strict, and why would you use it?

English: use strict is a directive that enables strict mode in JavaScript, which catches common coding mistakes such as assigning values to undeclared variables and prevents the use of some problematic features. It is useful for writing more secure and optimized code.

Chinese: use strict是一条指令,用于在JavaScript中启用严格模式,捕获常见的编码错误,如将值分配给未声明的变量,并防止使用一些有问题的功能。它有助于编写更安全和优化的代码。


38. What is the difference between == and === in JavaScript?

English: == checks for equality with type coercion, meaning it converts the operands to the same type before comparing. === checks for strict equality, meaning both type and value must be the same without type coercion.

Chinese: ==通过类型转换检查相等性,意味着在比较之前将操作数转换为相同的类型。===检查严格相等,意味着类型和值都必须相同,没有类型转换。


39. What is the event loop in JavaScript?

English: The event loop is responsible for handling asynchronous operations in JavaScript. It continuously checks the call stack and the message queue. When the call stack is empty, it dequeues tasks from the message queue and executes them, allowing asynchronous code to run.

Chinese: 事件循环负责处理JavaScript中的异步操作。它持续检查调用栈和消息队列。当调用栈为空时,它会从消息队列中取出任务并执行它们,从而允许异步代码运行。


40. How does the fetch API work in JavaScript?

English: The fetch() API is used to make network requests, returning a Promise that resolves to the Response object representing the response to the request. It provides an easier and cleaner way to handle HTTP requests compared to older methods like XMLHttpRequest.

Chinese: fetch() API用于发出网络请求,返回一个Promise,该Promise解析为表示请求响应的Response对象。它比旧方法如XMLHttpRequest提供了一种更简单和更清晰的处理HTTP请求的方式。


41. What is the difference between let, var, and const in JavaScript?

English: var has function scope and is hoisted, meaning it can be used before its declaration. let and const have block scope. let allows reassignment, while const does not allow reassignment after initialization.

Chinese: var具有函数作用域并且提升,这意味着它可以在声明之前使用。letconst具有块作用域。let允许重新赋值,而const在初始化后不允许重新赋值。


42. What is the difference between call, apply, and bind in JavaScript?

English: call() invokes a function with a specified this context and arguments individually. apply() is similar but takes arguments as an array. bind() returns a new function with a bound this context but does not execute it immediately.

Chinese: call()使用指定的this上下文和单独的参数调用函数。apply()类似,但它接受参数数组。bind()返回一个绑定了this上下文的新函数,但不会立即执行。


43. What is currying in JavaScript, and why is it useful?

English: Currying is the process of transforming a function with multiple arguments into a sequence of functions, each taking a single argument. It allows for partial application of functions, which can be useful in scenarios where some arguments are known in advance.

Chinese: 柯里化是将具有多个参数的函数转换为一系列函数的过程,每个函数只接受一个参数。这允许部分应用函数,在某些参数已知的情况下非常有用。


44. What is prototype in JavaScript?

English: The prototype in JavaScript is an object that is associated with every function and object. Objects inherit properties and methods from their prototype. This allows for object-oriented programming by sharing behaviors across objects.

Chinese: JavaScript中的prototype是与每个函数和对象相关联的对象。对象从它们的原型中继承属性和方法。这允许通过在对象之间共享行为来实现面向对象的编程。


45. How does localStorage differ from sessionStorage?

English: localStorage persists data even after the browser is closed and reopened, while sessionStorage only stores data for the duration of the browser session (until the browser is closed). Both store key-value pairs but have different lifetimes.

Chinese: localStorage在浏览器关闭和重新打开后仍然持久化数据,而sessionStorage只在浏览器会话期间存储数据(直到浏览器关闭)。两者都存储键值对,但具有不同的生命周期。


46. What are higher-order functions in JavaScript?

English: Higher-order functions are functions that take other functions as arguments, return a function, or both. Examples include map(), filter(), and reduce(). They enable more abstract and functional programming patterns in JavaScript.

Chinese: 高阶函数是接受其他函数作为参数、返回函数或两者兼有的函数。示例包括map()filter()reduce()。它们使JavaScript能够实现更抽象的函数式编程模式。


47. How do async and await work in JavaScript?

English: async and await provide a way to write asynchronous code that looks synchronous. Functions marked with async return a promise, and await is used to pause the execution until the promise resolves, allowing you to write cleaner, more readable asynchronous code.

Chinese: asyncawait

提供了一种编写看起来像同步的异步代码的方法。标记为async的函数返回一个Promise,await用于暂停执行直到Promise解决,从而允许您编写更清晰、更可读的异步代码。


48. How does the JavaScript event loop work?

English: The event loop is responsible for handling asynchronous operations in JavaScript. It continuously checks the call stack and the message queue. When the call stack is empty, the event loop dequeues tasks from the message queue and executes them.

Chinese: 事件循环负责处理JavaScript中的异步操作。它持续检查调用栈和消息队列。当调用栈为空时,事件循环会从消息队列中取出任务并执行它们。


49. What is the difference between synchronous and asynchronous code in JavaScript?

English: Synchronous code executes sequentially, where each operation waits for the previous one to complete. Asynchronous code allows operations to run independently, with the result of one operation not blocking the next. Asynchronous operations are handled using callbacks, promises, or async/await.

Chinese: 同步代码按顺序执行,每个操作等待前一个操作完成。异步代码允许操作独立运行,一个操作的结果不会阻塞下一个操作。异步操作使用回调函数、Promise或async/await处理。


50. What is deep cloning, and how do you implement it in JavaScript?

English: Deep cloning is the process of creating a complete copy of an object, including nested objects. It can be done using JSON.stringify() and JSON.parse() for simple objects, or using libraries like Lodash’s cloneDeep() for more complex objects that handle circular references and functions.

Chinese: 深拷贝是创建对象的完整副本的过程,包括嵌套对象。对于简单对象,可以使用JSON.stringify()JSON.parse()实现,或者使用像Lodash的cloneDeep()这样的库来处理复杂对象,包括循环引用和函数。


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *