Top JavaScript Interview Questions (Updated for 2026)
Updated for 2026! This repository contains a few hundred curated JavaScript interview questions with high quality answers for acing your Front End Engineer interviews, brought to you by GreatFrontEnd.
Looking for more? Read our blog post 50+ must-know JavaScript interview questions and answers compiled from ex-FAANG interviewers.
This repository is a public mirror. GreatFrontEnd’s main repository is the source of truth for question content; use this repository’s Issues to report problems instead of opening content pull requests.
The questions are divided into three sections:
- Top questions: List of the most important JavaScript interview questions that are commonly-asked during Front End Developer interviews. This README displays the concise version of the answers and links are provided to the full version of answers for further learning. If you are are short on time, start with this section.
- All questions: Comprehensive and elaborate list of JavaScript interview questions that ranges from basic to advanced topics. The answers in this section are more concise. This section is useful if you rusty with JavaScript concepts and need a refresher.
- Questions by difficulty: Questions categorized by difficulty – basic, intermediate, advanced.
Table of Contents (Top Questions)
This list contains the top essential questions that are frequently-asked during Front End Engineer interviews. Concise versions of the answers are presented here with links to elaborate versions for further reading. This section is great if you need a quick refresher of the most important concepts.
Table of Contents (All Questions)
This list contains a longer list of important JavaScript questions. Not all of them will be asked during Front End Engineer interviews but they provide a well-rounded review of JavaScript concepts ranging from beginner to advanced topics.
| No. |
Questions |
Level |
| 1 |
What are the various data types in JavaScript? |
Basic |
| 2 |
How do you check the data type of a variable? |
Basic |
| 3 |
What’s the difference between a JavaScript variable that is: null, undefined or undeclared? |
Basic |
| 4 |
What are the differences between JavaScript variables created using let, var or const? |
Basic |
| 5 |
Why is it, in general, a good idea to leave the global JavaScript scope of a website as-is and never touch it? |
Intermediate |
| 6 |
How do you convert a string to a number in JavaScript? |
Basic |
| 7 |
What are template literals and how are they used? |
Basic |
| 8 |
Explain the concept of tagged templates |
Intermediate |
| 9 |
What is the spread operator and how is it used? |
Basic |
| 10 |
What are Symbols used for in JavaScript? |
Intermediate |
| 11 |
What are proxies in JavaScript used for? |
Advanced |
| 12 |
Explain the concept of “hoisting” in JavaScript |
Basic |
| 13 |
Explain the difference in hoisting between var, let, and const |
Basic |
| 14 |
How does hoisting affect function declarations and expressions? |
Advanced |
| 15 |
What are the potential issues caused by hoisting? |
Intermediate |
| 16 |
How can you avoid problems related to hoisting? |
Basic |
| 17 |
What is the difference between == and === in JavaScript? |
Basic |
| 18 |
What language constructs do you use for iterating over object properties and array items in JavaScript? |
Basic |
| 19 |
What is the purpose of the break and continue statements? |
Basic |
| 20 |
What is the ternary operator and how is it used? |
Basic |
| 21 |
How do you access the index of an element in an array during iteration? |
Basic |
| 22 |
What is the purpose of the switch statement? |
Basic |
| 23 |
What are rest parameters and how are they used? |
Basic |
| 24 |
Explain the concept of the spread operator and its uses |
Basic |
| 25 |
What are the benefits of using spread syntax in JavaScript and how is it different from rest syntax? |
Basic |
| 26 |
What are iterators and generators in JavaScript and what are they used for? |
Advanced |
| 27 |
Explain the differences on the usage of foo between function foo() {} and var foo = function() {} in JavaScript |
Basic |
| 28 |
What is the difference between a parameter and an argument? |
Basic |
| 29 |
Explain the concept of hoisting with regards to functions |
Basic |
| 30 |
What’s the difference between .call and .apply in JavaScript? |
Basic |
| 31 |
Can you offer a use case for the new arrow => function syntax? |
Basic |
| 32 |
Difference between: function Person(){}, const person = Person(), and const person = new Person() in JavaScript? |
Basic |
| 33 |
What is the definition of a higher-order function in JavaScript? |
Basic |
| 34 |
What are callback functions and how are they used? |
Basic |
| 35 |
What’s a typical use case for anonymous functions in JavaScript? |
Intermediate |
| 36 |
What is recursion and how is it used in JavaScript? |
Basic |
| 37 |
What are default parameters and how are they used? |
Basic |
| 38 |
Explain why the following doesn’t work as an IIFE: function foo(){}();. What needs to be changed to properly make it an IIFE? |
Advanced |
| 39 |
What are the various ways to create objects in JavaScript? |
Basic |
| 40 |
Explain the difference between dot notation and bracket notation for accessing object properties |
Basic |
| 41 |
What are the different methods for iterating over an array? |
Basic |
| 42 |
How do you add, remove, and update elements in an array? |
Basic |
| 43 |
What are the different ways to copy an object or an array? |
Basic |
| 44 |
Explain the difference between shallow copy and deep copy |
Basic |
| 45 |
What are the advantages of using the spread operator with arrays and objects? |
Basic |
| 46 |
How do you check if an object has a specific property? |
Basic |
| 47 |
Explain the difference between mutable and immutable objects in JavaScript |
Intermediate |
| 48 |
Explain the concept of destructuring assignment for objects and arrays |
Basic |
| 49 |
What is Object.freeze() for? |
Intermediate |
| 50 |
What is Object.seal() for? |
Intermediate |
| 51 |
What is Object.preventExtensions() for? |
Intermediate |
| 52 |
What are JavaScript object getters and setters for? |
Intermediate |
| 53 |
What are JavaScript object property flags and descriptors? |
Advanced |
| 54 |
How do you reliably determine whether an object is empty? |
Basic |
| 55 |
What is the event loop in JavaScript runtimes? |
Basic |
| 56 |
Explain the difference between synchronous and asynchronous functions in JavaScript |
Basic |
| 57 |
Explain the concept of a callback function in asynchronous operations |
Basic |
| 58 |
What are Promises and how do they work? |
Basic |
| 59 |
Explain the different states of a Promise |
Intermediate |
| 60 |
What are the pros and cons of using Promises instead of callbacks in JavaScript? |
Intermediate |
| 61 |
What is the use of Promise.all() |
Basic |
| 62 |
How is Promise.all() different from Promise.allSettled()? |
Intermediate |
| 63 |
What is async/await and how does it simplify asynchronous code? |
Intermediate |
| 64 |
How do you handle errors in asynchronous operations? |
Basic |
| 65 |
Explain the concept of a microtask queue |
Intermediate |
| 66 |
What is the difference between setTimeout(), setImmediate(), and process.nextTick()? |
Intermediate |
| 67 |
Explain how prototypal inheritance works in JavaScript |
Basic |
| 68 |
What is the prototype chain and how does it work? |
Intermediate |
| 69 |
Explain the difference between classical inheritance and prototypal inheritance |
Basic |
| 70 |
Explain the concept of inheritance in ES2015 classes |
Basic |
| 71 |
What is the purpose of the new keyword? |
Basic |
| 72 |
How do you create a constructor function? |
Basic |
| 73 |
What are the differences between JavaScript ES2015 classes and ES5 function constructors? |
Basic |
| 74 |
What advantage is there for using the JavaScript arrow syntax for a method in a constructor? |
Basic |
| 75 |
Why might you want to create static class members in JavaScript? |
Intermediate |
| 76 |
What is a closure in JavaScript, and how/why would you use one? |
Intermediate |
| 77 |
Explain the concept of lexical scoping |
Basic |
| 78 |
Explain the concept of scope in JavaScript |
Basic |
| 79 |
How can closures be used to create private variables? |
Basic |
| 80 |
What are the potential pitfalls of using closures? |
Intermediate |
| 81 |
Explain the difference between global scope, function scope, and block scope |
Basic |
| 82 |
Explain how this works in JavaScript |
Basic |
| 83 |
Explain Function.prototype.bind in JavaScript |
Basic |
| 84 |
Explain the different ways the this keyword can be bound |
Intermediate |
| 85 |
What are the common pitfalls of using the this keyword? |
Basic |
| 86 |
Explain the concept of this binding in event handlers |
Basic |
| 87 |
What is the DOM and how is it structured? |
Basic |
| 88 |
What’s the difference between an “attribute” and a “property” in the DOM? |
Intermediate |
| 89 |
Explain the difference between document.querySelector() and document.getElementById() |
Basic |
| 90 |
How do you add, remove, and modify HTML elements using JavaScript? |
Basic |
| 91 |
What are event listeners and how are they used? |
Basic |
| 92 |
Explain the event phases in a browser |
Intermediate |
| 93 |
Describe event bubbling in JavaScript and browsers |
Basic |
| 94 |
Describe event capturing in JavaScript and browsers |
Basic |
| 95 |
Explain event delegation in JavaScript |
Basic |
| 96 |
How do you prevent the default behavior of an event? |
Basic |
| 97 |
What is the difference between event.preventDefault() and event.stopPropagation()? |
Intermediate |
| 98 |
What is the difference between mouseenter and mouseover event in JavaScript and browsers? |
Basic |
| 99 |
What is the difference between innerHTML and textContent? |
Intermediate |
| 100 |
How do you manipulate CSS styles using JavaScript? |
Basic |
| 101 |
Describe the difference between <script>, <script async> and <script defer> |
Basic |
| 102 |
What is the difference between the Window object and the Document object? |
Intermediate |
| 103 |
Describe the difference between a cookie, sessionStorage and localStorage in browsers |
Basic |
| 104 |
How do you make an HTTP request using the Fetch API? |
Basic |
| 105 |
What are the different ways to make an API call in JavaScript? |
Basic |
| 106 |
Explain AJAX in as much detail as possible |
Basic |
| 107 |
What are the advantages and disadvantages of using AJAX? |
Basic |
| 108 |
What are the differences between XMLHttpRequest and fetch() in JavaScript and browsers? |
Basic |
| 109 |
How do you abort a web request using AbortController in JavaScript? |
Intermediate |
| 110 |
Explain how JSONP works (and how it’s not really Ajax) |
Intermediate |
| 111 |
What are workers in JavaScript used for? |
Advanced |
| 112 |
Explain the concept of the Web Socket API |
Intermediate |
| 113 |
What are JavaScript polyfills for? |
Advanced |
| 114 |
How do you detect if JavaScript is disabled on a page? |
Intermediate |
| 115 |
What is the Intl namespace object for? |
Intermediate |
| 116 |
How do you validate form elements using the Constraint Validation API? |
Advanced |
| 117 |
How do you use window.history API? |
Basic |
| 118 |
How do <iframe> on a page communicate? |
Intermediate |
| 119 |
Difference between document load event and document DOMContentLoaded event? |
Intermediate |
| 120 |
How do you redirect to a new page in JavaScript? |
Basic |
| 121 |
How do you get the query string values of the current page in JavaScript? |
Basic |
| 122 |
What are server-sent events? |
Advanced |
| 123 |
What are Progressive Web Applications (PWAs)? |
Intermediate |
| 124 |
What are modules and why are they useful? |
Basic |
| 125 |
Explain the differences between CommonJS modules and ES modules in JavaScript |
Intermediate |
| 126 |
How do you import and export modules in JavaScript? |
Basic |
| 127 |
What are the benefits of using a module bundler? |
Intermediate |
| 128 |
Explain the concept of tree shaking in module bundling |
Intermediate |
| 129 |
What are the metadata fields of a module? |
Intermediate |
| 130 |
What do you think of CommonJS vs ESM? |
Basic |
| 131 |
What are the different types of errors in JavaScript? |
Intermediate |
| 132 |
How do you handle errors using try...catch blocks? |
Basic |
| 133 |
What is the purpose of the finally block? |
Basic |
| 134 |
How can you create custom error objects? |
Intermediate |
| 135 |
Explain the concept of error propagation in JavaScript |
Intermediate |
| 136 |
What is currying and how does it work? |
Intermediate |
| 137 |
Explain the concept of partial application |
Intermediate |
| 138 |
What are the benefits of using currying and partial application? |
Intermediate |
| 139 |
Provide some examples of how currying and partial application can be used |
Basic |
| 140 |
How do currying and partial application differ from each other? |
Intermediate |
| 141 |
What are Sets and Maps and how are they used? |
Basic |
| 142 |
What are the differences between Map/Set and WeakMap/WeakSet in JavaScript? |
Basic |
| 143 |
How do you convert a Set to an array in JavaScript? |
Basic |
| 144 |
What is the difference between a Map object and a plain object in JavaScript? |
Basic |
| 145 |
How do Sets and Maps handle equality checks for objects? |
Basic |
| 146 |
What are some common performance bottlenecks in JavaScript applications? |
Intermediate |
| 147 |
Explain the concept of debouncing and throttling |
Basic |
| 148 |
How can you optimize DOM manipulation for better performance? |
Advanced |
| 149 |
What are some techniques for reducing reflows and repaints? |
Advanced |
| 150 |
Explain the concept of lazy loading and how it can improve performance |
Basic |
| 151 |
What are Web Workers and how can they be used to improve performance? |
Advanced |
| 152 |
Explain the concept of caching and how it can be used to improve performance |
Basic |
| 153 |
What are some tools that can be used to measure and analyze JavaScript performance? |
Advanced |
| 154 |
How can you optimize network requests for better performance? |
Advanced |
| 155 |
What are the different types of testing in software development? |
Intermediate |
| 156 |
Explain the difference between unit testing, integration testing, and end-to-end testing |
Intermediate |
| 157 |
What are some popular JavaScript testing frameworks? |
Basic |
| 158 |
How do you write unit tests for JavaScript code? |
Intermediate |
| 159 |
Explain the concept of test-driven development (TDD) |
Intermediate |
| 160 |
What are mocks and stubs and how are they used in testing? |
Advanced |
| 161 |
How can you test asynchronous code in JavaScript? |
Intermediate |
| 162 |
What are some best practices for writing maintainable and effective tests in JavaScript? |
Intermediate |
| 163 |
Explain the concept of code coverage and how it can be used to assess test quality |
Intermediate |
| 164 |
What are some tools that can be used for JavaScript testing? |
Basic |
| 165 |
What are design patterns and why are they useful? |
Basic |
| 166 |
Explain the concept of the Singleton pattern |
Basic |
| 167 |
What is the Factory pattern and how is it used? |
Intermediate |
| 168 |
Explain the Observer pattern and its use cases |
Intermediate |
| 169 |
What is the Module pattern and how does it help with encapsulation? |
Intermediate |
| 170 |
Explain the concept of the Prototype pattern |
Basic |
| 171 |
What is the Decorator pattern and how is it used? |
Intermediate |
| 172 |
Explain the concept of the Strategy pattern |
Intermediate |
| 173 |
What is the Command pattern and how is it used? |
Intermediate |
| 174 |
Why is extending built-in JavaScript objects not a good idea? |
Intermediate |
| 175 |
What is Cross-Site Scripting (XSS) and how can you prevent it? |
Intermediate |
| 176 |
Explain the concept of Cross-Site Request Forgery (CSRF) and its mitigation techniques |
Intermediate |
| 177 |
How can you prevent SQL injection vulnerabilities in JavaScript applications? |
Intermediate |
| 178 |
What are some best practices for handling sensitive data in JavaScript? |
Intermediate |
| 179 |
Explain the concept of Content Security Policy (CSP) and how it enhances security |
Intermediate |
| 180 |
What are some common security headers and their purpose? |
Intermediate |
| 181 |
How can you prevent clickjacking attacks? |
Advanced |
| 182 |
Explain the concept of input validation and its importance in security |
Intermediate |
| 183 |
What are some tools and techniques for identifying security vulnerabilities in JavaScript code? |
Intermediate |
| 184 |
How can you implement secure authentication and authorization in JavaScript applications? |
Advanced |
| 185 |
Explain the same-origin policy with regards to JavaScript |
Intermediate |
| 186 |
What is 'use strict'; (strict mode) in JavaScript for? |
Advanced |
| 187 |
What tools and techniques do you use for debugging JavaScript code? |
Intermediate |
| 188 |
How does JavaScript garbage collection work? |
Advanced |
| 189 |
Explain what a single page app is and how to make one SEO-friendly |
Intermediate |
| 190 |
How can you share code between JavaScript files? |
Basic |
| 191 |
How do you organize your code? |
Intermediate |
| 192 |
What are some of the advantages and disadvantages of using TypeScript and compile-to-JavaScript languages |
Advanced |
| 193 |
When would you use document.write()? |
Advanced |
Top Questions with Answers
Explain the concept of “hoisting” in JavaScript
“Hoisting” is informal shorthand for how JavaScript creates and initializes bindings while it instantiates a scope, before evaluating that scope’s statements. The engine does not move source text.
- Variable declarations (
var): The binding is created and initialized to undefined before statements run. Its assignment still happens at the declaration’s source location.
- Variable declarations (
let and const): The binding is created but remains uninitialized in the temporal dead zone (TDZ) until evaluation reaches the declaration. Accessing it earlier throws ReferenceError.
- Function expressions (
var): The var binding initially contains undefined; the function is created only when the expression is evaluated.
- Function declarations (
function): The binding is initialized with the function during scope setup, so it can be called before its declaration appears in source order.
- Class declarations (
class): The binding exists during scope setup but remains in the TDZ until the class declaration is evaluated.
- Import declarations (
import): Imported bindings are linked before module evaluation. Dependencies normally evaluate before the importing module’s body, although cycles can expose an uninitialized binding.
The following behavior summarizes the result of accessing the variables before they are declared.
| Declaration |
Accessing before declaration |
var foo |
undefined |
let foo |
ReferenceError |
const foo |
ReferenceError |
class Foo |
ReferenceError |
var foo = function() { ... } |
undefined |
function foo() { ... } |
Normal |
import |
Normal, except some cycles |
Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
Back to top ↑
What are the differences between JavaScript variables created using let, var or const?
In JavaScript, let, var, and const are all keywords used to declare variables, but they differ significantly in terms of scope, initialization rules, whether they can be redeclared or reassigned, and the behavior when they are accessed before declaration:
| Behavior |
var |
let |
const |
| Scope |
Function or Global |
Block |
Block |
| Initialization |
Optional |
Optional |
Required |
| Redeclaration |
Yes |
No |
No |
| Reassignment |
Yes |
Yes |
No |
| Accessing before declaration |
undefined |
ReferenceError |
ReferenceError |
Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
Back to top ↑
What is the difference between == and === in JavaScript?
== is the abstract equality operator while === is the strict equality operator. == first checks the operand types. When they match, it compares the values without type coercion, just like ===. When the types differ, it follows the Abstract Equality Comparison algorithm, which may convert one or both operands. === never performs type coercion and returns false whenever the operand types differ. === is generally preferred in application code because it eliminates a class of bugs caused by unexpected coercion. The most common exception is x == null, which checks for both null and undefined in a single comparison.
| Operator |
== |
=== |
| Name |
Loose (abstract) equality operator |
Strict equality operator |
| Type coercion |
May occur when operand types differ |
No |
| Comparison behavior |
Same types: strict equality; different types: follow the abstract equality rules |
Different types: false; same types: compare without coercion |
Don’t confuse = with == and ===. = is the assignment operator and sets a variable’s value (x = 5); it does not compare anything.
Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
Back to top ↑
What is the event loop in JavaScript runtimes?
The event loop is the host runtime’s scheduling mechanism for coordinating JavaScript jobs, asynchronous operations, and (in browsers) rendering. A simplified browser turn works like this:
- The host runs one task, such as initial script evaluation, a timer callback, or an input-event callback. Function calls made by that task use the JavaScript agent’s call stack.
- Timers, networking, and other host APIs continue outside the currently executing JavaScript stack. When work becomes ready, the host queues a task or settles a promise, which queues its reactions as microtasks.
- After the current task finishes and its stack is empty, the runtime performs a microtask checkpoint. It drains promise reactions,
queueMicrotask() callbacks, and other microtasks, including microtasks added while the checkpoint is running.
- The browser may update rendering, then the host selects one eligible task and runs it. After that task, it performs another microtask checkpoint; it does not drain every task queue in one pass.
- These turns continue for the lifetime of the event loop. An unbounded microtask chain can delay later tasks and rendering.
Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
Back to top ↑
Explain event delegation in JavaScript
Event delegation is a technique in JavaScript where a single event listener is attached to a parent element instead of attaching event listeners to multiple child elements. When an event occurs on a child element, the event bubbles up the DOM tree, and the parent element’s event listener handles the event based on the target element.
Event delegation provides the following benefits:
- Fewer listeners: A single listener can reduce listener bookkeeping and per-item closures for very large collections. Whether that produces a measurable performance improvement depends on the page and should be profiled.
- Simplified event handling: With event delegation, you only need to write the event handling logic once in the parent element’s event listener. This makes the code more maintainable and easier to update.
- Dynamic element support: Event delegation automatically handles events for dynamically added or removed elements within the parent element. There’s no need to manually attach or remove event listeners when the DOM structure changes.
However, do note that:
- It is important to identify the target element that triggered the event.
- Not every event bubbles. For example,
focus/blur and mouseenter/mouseleave need capture-phase handling or bubbling alternatives such as focusin/focusout and mouseover/mouseout. Element scroll and resize generally need direct listeners.
Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
Back to top ↑
Explain how this works in JavaScript
For ordinary functions, this depends on the call form and any explicit binding. Arrow functions inherit this from their enclosing scope.
A longer explanation is that this follows these rules:
- If the
new keyword is used when calling the function, meaning the function was used as a function constructor, the this inside the function is the newly-created object instance.
- If
this is used in a class constructor, the this inside the constructor is the newly-created object instance.
- If
apply(), call(), or bind() is used to call/create a function, this inside the function is the object that is passed in as the argument.
- If a function is called as a method (e.g.
obj.method()); this is the object that the function is a property of.
- If a function is invoked as a free function invocation, meaning it was invoked without any of the conditions present above,
this is the global object. In the browser, the global object is the window object. If in strict mode ('use strict';), this will be undefined instead of the global object.
- If multiple of the above rules apply, the rule that is higher wins and will set the
this value.
- If the function is an ES2015 arrow function, it ignores all the rules above and receives the
this value of its surrounding scope at the time it is created.
For an in-depth explanation, do check out Arnav Aggrawal’s article on Medium.
Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
Back to top ↑
Describe the difference between a cookie, sessionStorage and localStorage in browsers
Cookies, localStorage, and sessionStorage all store data in the browser, but they differ in lifetime, scope, server interaction, and security controls. localStorage and sessionStorage implement the Web Storage API.
- Cookies: Small values that the browser sends with matching HTTP requests. They can be session or persistent cookies and support controls such as
HttpOnly, Secure, and SameSite.
localStorage: Origin-scoped string storage that persists until it is cleared and is shared by same-origin tabs and windows.
sessionStorage: Origin- and tab-scoped string storage for a page session. It survives reloads but is normally cleared when the tab or window closes.
Here’s a table summarizing the 3 client storage mechanisms.
| Property |
Cookie |
localStorage |
sessionStorage |
| Initiator |
Client or server. Server can use Set-Cookie header |
Client |
Client |
| Lifespan |
As specified |
Until deleted |
Until tab is closed |
| Persistent across browser sessions |
If a future expiry date is set |
Yes |
No |
| Sent to server with matching HTTP requests |
Yes, via the Cookie header |
No |
No |
| Typical storage limit |
About 4 KB per cookie |
Browser-dependent quota, commonly several MiB per origin |
Browser-dependent quota, commonly several MiB per origin |
| Access |
Across windows/tabs |
Across windows/tabs |
Same tab |
| Security |
JavaScript cannot access HttpOnly cookies |
None |
None |
Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
Back to top ↑
Describe the difference between <script>, <script async> and <script defer>
All of these ways (<script>, <script async>, and <script defer>) are used to load and execute JavaScript files in an HTML document, but they differ in how the browser handles loading and execution of the script:
<script> is the default way of including JavaScript. The browser blocks HTML parsing while the script is being downloaded and executed. The browser will not continue rendering the page until the script has finished executing.
<script async> downloads the script asynchronously, in parallel with parsing the HTML. Executes the script as soon as it is available, potentially interrupting the HTML parsing. Multiple <script async> tags do not wait for each other and execute in no particular order.
<script defer> downloads the script asynchronously, in parallel with parsing the HTML. However, the execution of the script is deferred until HTML parsing is complete, in the order they appear in the HTML.
The table compares four ways to load scripts, including module scripts:
| Feature |
<script> |
<script async> |
<script defer> |
<script type="module"> |
| Parsing behavior |
Blocks HTML parsing |
Downloads in parallel; execution still blocks parsing |
Downloads in parallel; execution deferred until after parsing |
Downloads in parallel; execution deferred until after parsing |
| Execution order |
In order of appearance |
Not guaranteed |
In order of appearance |
In order of appearance, with each script’s import dependencies resolved first |
| DOM state at execution |
Only earlier markup is parsed |
Depends on download timing |
Document parsing is complete |
Document parsing is complete |
Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
Back to top ↑
What’s the difference between a JavaScript variable that is: null, undefined or undeclared?
| Trait |
null |
undefined |
Undeclared |
| Meaning |
Explicitly set by the developer to indicate that a variable has no value |
Variable has been declared but not assigned a value |
Variable has not been declared at all |
Type (via typeof operator) |
'object' |
'undefined' |
'undefined' |
| Direct access/comparison |
Can compare with value === null |
Can compare with value === undefined |
Direct access throws ReferenceError; typeof undeclaredName returns 'undefined' |
Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
Back to top ↑
What’s the difference between .call and .apply in JavaScript?
.call and .apply are both used to invoke functions with a specific this context and arguments. The primary difference lies in how they accept arguments:
.call(thisArg, arg1, arg2, ...): Takes arguments individually.
.apply(thisArg, [argsArray]): Takes arguments as an array.
Assuming we have a function add, the function can be invoked using .call and .apply in the following manner:
function add(a, b) {
return a + b;
}
console.log(add.call(null, 1, 2));
console.log(add.apply(null, [1, 2]));
Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
Back to top ↑
Explain Function.prototype.bind in JavaScript
Function.prototype.bind is a method in JavaScript that allows you to create a new function with a specific this value and optional initial arguments. Its primary purpose is to:
- Binding
this value to preserve context: The primary purpose of bind is to bind the this value of a function to a specific object. When you call func.bind(thisArg), it creates a new function with the same body as func, but with this permanently bound to thisArg.
- Partial application of arguments:
bind also allows you to pre-specify arguments for the new function. Any arguments passed to bind after thisArg will be prepended to the arguments list when the new function is called.
- Method borrowing:
bind allows you to borrow methods from one object and apply them to another object, even if they were not originally designed to work with that object.
Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
Back to top ↑
What advantage is there for using the JavaScript arrow syntax for a method in a constructor?
The main advantage of using an arrow function as a method inside a constructor is that the value of this gets set at the time of the function creation and can’t change after that. When the constructor is used to create a new object, this will always refer to that object.
For example, let’s say we have a Person constructor that takes a first name as an argument and has two methods to console.log() that name, one as a regular function and one as an arrow function:
const Person = function (name) {
this.firstName = name;
this.sayName1 = function () {
console.log(this.firstName);
};
this.sayName2 = () => {
console.log(this.firstName);
};
};
const john = new Person('John');
const dave = new Person('Dave');
john.sayName1();
john.sayName2();
john.sayName1.call(dave);
john.sayName2.call(dave);
john.sayName1.apply(dave);
john.sayName2.apply(dave);
john.sayName1.bind(dave)();
john.sayName2.bind(dave)();
const detachedRegularMethod = john.sayName1;
try {
detachedRegularMethod();
} catch (error) {
console.log(error.name);
}
const detachedArrowMethod = john.sayName2;
detachedArrowMethod();
The main takeaway is that a regular function receives this from its call site, while an arrow captures it from the constructor call. The tradeoff is that this arrow function is created separately for every instance instead of being shared through the prototype, and callers cannot deliberately rebind it.
Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
Back to top ↑
Explain how prototypal inheritance works in JavaScript
Prototypal inheritance is property lookup by delegation. An object’s internal [[Prototype]] is another object or null; when an own property is missing, lookup continues along that chain. Inspect it with Object.getPrototypeOf() and create a deliberate link with Object.create() or class / extends. Avoid the legacy __proto__ accessor in application code, and avoid changing prototypes of existing objects in hot code because it can invalidate engine optimizations.
When a property is accessed on an object and if the property is not found on that object, the JavaScript engine looks at the object’s __proto__, and the __proto__'s __proto__ and so on, until it finds the property defined on one of the __proto__s or until it reaches the end of the prototype chain.
This behavior simulates classical inheritance, but it is really more of delegation than inheritance.
Here’s an example of prototypal inheritance:
function Animal(name) {
this.name = name;
}
Animal.prototype.makeSound = function () {
console.log('The ' + this.constructor.name + ' makes a sound.');
};
function Dog(name) {
Animal.call(this, name);
}
Object.setPrototypeOf(Dog.prototype, Animal.prototype);
Dog.prototype.bark = function () {
console.log('Woof!');
};
const bolt = new Dog('Bolt');
console.log(bolt.name);
bolt.makeSound();
bolt.bark();
Things to note are:
.makeSound is not defined on Dog, so the JavaScript engine goes up the prototype chain and finds .makeSound on the inherited Animal.
- In modern code,
class and extends are the preferred way to set up inheritance; they are syntactic sugar over this prototype mechanism.
Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
Back to top ↑
Difference between: function Person(){}, const person = Person(), and const person = new Person() in JavaScript?
function Person(){}: A function declaration in JavaScript. It can be used as a regular function or as a constructor.
const person = Person(): Calls Person as a regular function, not a constructor. If Person is intended to be a constructor, this will lead to unexpected behavior.
const person = new Person(): Creates a new instance of Person, correctly using the constructor function to initialize the new object.
| Aspect |
function Person(){} |
const person = Person() |
const person = new Person() |
| Type |
Function declaration |
Function call |
Constructor call |
| Usage |
Defines a function |
Invokes Person as a regular function |
Creates a new instance of Person |
| Instance Creation |
No instance created |
No instance created |
New instance created |
| Common Mistake |
N/A |
Misusing as constructor leading to undefined |
None (when used correctly) |
Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
Back to top ↑
Explain the differences on the usage of foo between function foo() {} and var foo = function() {} in JavaScript
function foo() {} is a function declaration while var foo = function() {} is a function expression. The key difference is that function declarations have their bodies hoisted but the bodies of function expressions are not (they have the same hoisting behavior as var-declared variables).
If you try to invoke a function expression before it is declared, you will get an Uncaught TypeError: XXX is not a function error.
Function declarations can be called in the enclosing scope even before they are declared.
foo();
function foo() {
console.log('FOOOOO');
}
Function expressions if called before they are declared will result in an error.
foo();
var foo = function () {
console.log('FOOOOO');
};
Another key difference is in the scope of the function name. Function expressions can be named by defining a name after the function keyword and before the parentheses. However, when using named function expressions, the function name is only accessible within the function itself. Trying to access it outside will result in a ReferenceError.
const myFunc = function namedFunc() {
console.log(namedFunc);
};
myFunc();
console.log(namedFunc);
Note: The examples use var due to legacy reasons. Function expressions can be defined using let and const, and the key difference is in the hoisting behavior of those keywords.
Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
Back to top ↑
What’s a typical use case for anonymous functions in JavaScript?
An anonymous function in JavaScript is a function that does not have any name associated with it. They are typically used as arguments to other functions or assigned to variables.
const arr = [-1, 0, 5, 6];
arr.filter((x) => x > 1);
They are often used as arguments to other functions, known as higher-order functions, which can take functions as input and return a function as output. Anonymous functions can access variables from the outer scope, a concept known as closures, allowing them to “close over” and remember the environment in which they were created.
(function () {
})();
setTimeout(function (</script></script></script></script></script></script></script></script></script></script></script></script></script></script></iframe></script></script></script></script></script></script>
> README 内容过长,已截取前 64 KB。完整内容请前往 GitHub 仓库查看。
评论