Back to Interview Prep

Chapter 34 of 34

Top 193 JavaScript Interview Questions

A rapid-fire reference covering the questions most likely to come up in a real interview - organized by topic and difficulty, with explanations that go beyond a one-line definition and a runnable code example for each one, so the concept sticks. Search or filter to find what you need, and share a direct link to any question.

Level:

Showing 193 of 193 questions

Questions reviewed0/193 · 0%

The first 15 of 193 questions are free to read. Sign up free to unlock every answer and track your progress.

Unlock all 193

In JavaScript, data types can be categorized into primitive and non-primitive types. Primitive data types: Number (represents both integers and floating-point numbers), String (represents sequences of characters), Boolean (represents true or false values), Undefined (a variable that has been declared but not assigned a value), Null (represents the intentional absence of any object value), Symbol (a unique and immutable value used as object property keys), BigInt (represents integers with arbitrary precision). Non-primitive (reference) data types: Object (used to store collections of data), Array (an ordered collection of data), Function (a callable object), Date (represents dates and times), RegExp (represents regular expressions), Map (a collection of keyed data items), Set (a collection of unique values). The primitive types store a single value, while non-primitive types can store collections of data or complex entities.

To check the data type of a variable in JavaScript, you can use the typeof operator. For example, typeof variableName will return a string indicating the type of the variable, such as "string", "number", "boolean", "object", "function", "undefined", or "symbol". For arrays and null, you can use Array.isArray(variableName) and variableName === null, respectively.

Comparing null, undefined, and an undeclared variable across meaning, type, and equality comparison: Meaning - null is explicitly set by the developer to indicate that a variable has no value; undefined means a variable has been declared but not assigned a value; an undeclared variable has not been declared at all. Type (via the typeof operator) - typeof null returns 'object'; typeof undefined returns 'undefined'; typeof on an undeclared variable also returns 'undefined'. Equality comparison - null == undefined is true, and undefined == null is true, but referencing an undeclared variable throws a ReferenceError.

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. Comparing var, let, and const: Scope - var is function or global scoped, while let and const are block scoped. Initialization - var and let initialization is optional, while const requires an initial value. Redeclaration - var can be redeclared, but let and const cannot. Reassignment - var and let can be reassigned, but const cannot. Accessing before declaration - var yields undefined, while both let and const throw a ReferenceError.

JavaScript that is executed in the browser has access to the global scope (the window object). In general it's a good software engineering practice to not pollute the global namespace unless you are working on a feature that truly needs to be global - it is needed by the entire page. Several reasons to avoid touching the global scope: naming conflicts (sharing the global scope across scripts can cause conflicts and bugs when new global variables or changes are introduced); a cluttered global namespace (keeping the global namespace minimal avoids making the codebase hard to manage and maintain); scope leaks (unintentional references to global variables in closures or event handlers can cause memory leaks and performance issues); modularity and encapsulation (good design promotes keeping variables and functions within their specific scopes, enhancing organization, reusability, and maintainability); security concerns (global variables are accessible by all scripts, including potentially malicious ones, posing security risks, especially if sensitive data is stored there); and compatibility and portability (heavy reliance on global variables reduces code portability and integration ease with other libraries or frameworks). Best practices to avoid global scope pollution include: using local variables (declare variables within functions or blocks using var, let, or const to limit their scope); passing variables as function parameters (maintain encapsulation by passing variables as parameters instead of accessing them globally); using immediately invoked function expressions - IIFEs (create new scopes with IIFEs to prevent adding variables to the global scope); and using modules (encapsulate code with module systems to maintain separate scopes and manageability).

In JavaScript, you can convert a string to a number using several methods. The most common ones are Number(), parseInt(), parseFloat(), and the unary plus operator (+). For example, Number("123") converts the string "123" to the number 123, and parseInt("123.45") converts the string "123.45" to the integer 123.

Template literals are a feature in JavaScript that allow for easier string interpolation and multi-line strings. They are enclosed by backticks (`) instead of single or double quotes. You can embed expressions within template literals using ${expression} syntax.

Example

const myName = 'John';
const greeting = `Hello, ${myName}!`;
console.log(greeting); // Output: Hello, John!

Tagged templates in JavaScript allow you to parse template literals with a function. The function receives the literal strings and the values as arguments, enabling custom processing of the template.

Example

function tag(strings, ...values) {
  return strings[0] + values[0] + strings[1] + values[1] + strings[2];
}

const result = tag`Hello ${'world'}! How are ${'you'}?`;
console.log(result); // "Hello world! How are you?"

The spread operator, represented by three dots (...), is used in JavaScript to expand iterable objects like arrays or strings into individual elements. It can also be used to spread object properties. For example, you can use it to combine arrays, copy arrays, or pass array elements as arguments to a function.

Example

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const combinedObj = { ...obj1, ...obj2 };
console.log(combinedObj); // { a: 1, b: 2, c: 3, d: 4 }

Symbols in JavaScript are a new primitive data type introduced in ES6 (ECMAScript 2015). They are unique and immutable identifiers used primarily for object property keys to avoid name collisions. These values can be created using the Symbol(...) function, and each Symbol value is guaranteed to be unique, even if they have the same key or description. Symbol properties are not enumerable in for...in loops or Object.keys(), making them suitable for creating private or internal object state. Note: the Symbol() function must be called without the new keyword - it is not exactly a constructor because it can only be called as a function instead of with new Symbol().

Example

let sym1 = Symbol();
let sym2 = Symbol('myKey');

console.log(typeof sym1); // "symbol"
console.log(sym1 === sym2); // false, because each symbol is unique

let obj = {};
let sym = Symbol('uniqueKey');

obj[sym] = 'value';
console.log(obj[sym]); // "value"

In JavaScript, a proxy is an object that acts as an intermediary between an object and the code. Proxies are used to intercept and customize the fundamental operations of JavaScript objects, such as property access, assignment, function invocation, and more. Use cases include: property access interception (intercept and customize property access on an object), with sub-cases such as property assignment validation (validate property values before they are set on the target object), logging and debugging (create wrappers for logging and debugging interactions with an object), creating reactive systems (trigger updates in other parts of your application when object properties change, as in data binding), data transformation (transforming data being set or retrieved from an object), and mocking and stubbing in tests (create mock or stub objects for testing purposes, allowing you to isolate dependencies and focus on the unit under test); function invocation interception (used to cache and return the result of frequently accessed methods if they involve network calls or computationally intensive logic, improving performance); and dynamic property creation (useful for defining properties on-the-fly with default values and avoiding storing redundant data in objects).

Example

const myObject = {
  name: 'John',
  age: 42,
};

const handler = {
  get: function (target, prop, receiver) {
    console.log(`Someone accessed property "${prop}"`);
    return target[prop];
  },
};

const proxiedObject = new Proxy(myObject, handler);

console.log(proxiedObject.name);
// Someone accessed property "name"
// 'John'

console.log(proxiedObject.age);
// Someone accessed property "age"
// 42

Hoisting is a JavaScript mechanism where variable and function declarations are moved ("hoisted") to the top of their containing scope during the compile phase. Variable declarations (var) - declarations are hoisted, but not initializations; the value of the variable is undefined if accessed before initialization. Variable declarations (let and const) - declarations are hoisted, but not initialized; accessing them results in a ReferenceError until the actual declaration is encountered. Function expressions assigned to var - declarations are hoisted, but not initializations; the value is undefined if accessed before initialization. Function declarations (function) - both the declaration and definition are fully hoisted. Class declarations (class) - declarations are hoisted, but not initialized; accessing them results in a ReferenceError until the actual declaration is encountered. Import declarations (import) - declarations are hoisted, and the side effects of importing the module are executed before the rest of the code. Summary of accessing before declaration: var foo results in undefined; let foo throws a ReferenceError; const foo throws a ReferenceError; class Foo throws a ReferenceError; var foo = function() {...} results in undefined; function foo() {...} works normally; and import works normally.

var declarations are hoisted to the top of their scope and initialized with undefined, allowing them to be used before their declaration. let and const declarations are also hoisted but are not initialized, resulting in a ReferenceError if accessed before their declaration. const additionally requires an initial value at the time of declaration.

Hoisting in JavaScript means that function declarations are moved to the top of their containing scope during the compile phase, making them available throughout the entire scope. This allows you to call a function before it is defined in the code. However, function expressions are not hoisted in the same way. If you try to call a function expression before it is defined, you will get an error because the variable holding the function is hoisted but not its assignment.

Example

// Function declaration
console.log(foo()); // Works fine
function foo() {
  return 'Hello';
}

// Function expression
console.log(bar()); // Throws TypeError: bar is not a function
var bar = function () {
  return 'Hello';
};

Hoisting can lead to unexpected behavior in JavaScript because variable and function declarations are moved to the top of their containing scope during the compilation phase. This can result in undefined values for variables if they are used before their declaration and can cause confusion with function declarations and expressions.

Example

console.log(a); // undefined
var a = 5;

console.log(b);
// ReferenceError: Cannot access 'b' before initialization
let b = 10;
16.How can you avoid problems related to hoisting?17.What is the difference between == and === in JavaScript?18.What language constructs do you use for iterating over object properties and array items in JavaScript?19.What is the purpose of the break and continue statements?20.What is the ternary operator and how is it used?21.How do you access the index of an element in an array during iteration?22.What is the purpose of the switch statement?23.What are rest parameters and how are they used?24.Explain the concept of the spread operator and its uses25.What are the benefits of using spread syntax in JavaScript and how is it different from rest syntax?26.What are iterators and generators in JavaScript and what are they used for?27.Explain the differences on the usage of foo between function foo() {} and var foo = function() {} in JavaScript28.What is the difference between a parameter and an argument?29.Explain the concept of hoisting with regards to functions30.What's the difference between .call and .apply in JavaScript?31.Can you offer a use case for the new arrow => function syntax?32.Difference between: function Person(){}, const person = Person(), and const person = new Person() in JavaScript?33.What is the definition of a higher-order function in JavaScript?34.What are callback functions and how are they used?35.What's a typical use case for anonymous functions in JavaScript?36.What is recursion and how is it used in JavaScript?37.What are default parameters and how are they used?38.Explain why the following doesn't work as an IIFE: function foo(){}(); . What needs to be changed to properly make it an IIFE?39.What are the various ways to create objects in JavaScript?40.Explain the difference between dot notation and bracket notation for accessing object properties41.What are the different methods for iterating over an array?42.How do you add, remove, and update elements in an array?43.What are the different ways to copy an object or an array?44.Explain the difference between shallow copy and deep copy45.What are the advantages of using the spread operator with arrays and objects?46.How do you check if an object has a specific property?47.Explain the difference between mutable and immutable objects in JavaScript48.Explain the concept of destructuring assignment for objects and arrays49.What is Object.freeze() for?50.What is Object.seal() for?51.What is Object.preventExtensions() for?52.What are JavaScript object getters and setters for?53.What are JavaScript object property flags and descriptors?54.How do you reliably determine whether an object is empty?55.What is the event loop in JavaScript runtimes?56.Explain the difference between synchronous and asynchronous functions in JavaScript57.Explain the concept of a callback function in asynchronous operations58.What are Promises and how do they work?59.Explain the different states of a Promise60.What are the pros and cons of using Promises instead of callbacks in JavaScript?61.What is the use of Promise.all()62.How is Promise.all() different from Promise.allSettled()?63.What is async/await and how does it simplify asynchronous code?64.How do you handle errors in asynchronous operations?65.Explain the concept of a microtask queue66.What is the difference between setTimeout(), setImmediate(), and process.nextTick()?67.Explain how prototypal inheritance works in JavaScript68.What is the prototype chain and how does it work?69.Explain the difference between classical inheritance and prototypal inheritance70.Explain the concept of inheritance in ES2015 classes71.What is the purpose of the new keyword?72.How do you create a constructor function?73.What are the differences between JavaScript ES2015 classes and ES5 function constructors?74.What advantage is there for using the JavaScript arrow syntax for a method in a constructor?75.Why might you want to create static class members in JavaScript?76.What is a closure in JavaScript, and how/why would you use one?77.Explain the concept of lexical scoping78.Explain the concept of scope in JavaScript79.How can closures be used to create private variables?80.What are the potential pitfalls of using closures?81.Explain the difference between global scope, function scope, and block scope82.Explain how this works in JavaScript83.Explain Function.prototype.bind in JavaScript84.Explain the different ways the this keyword can be bound85.What are the common pitfalls of using the this keyword?86.Explain the concept of this binding in event handlers87.What is the DOM and how is it structured?88.What's the difference between an "attribute" and a "property" in the DOM?89.Explain the difference between document.querySelector() and document.getElementById()90.How do you add, remove, and modify HTML elements using JavaScript?91.What are event listeners and how are they used?92.Explain the event phases in a browser93.Describe event bubbling in JavaScript and browsers94.Describe event capturing in JavaScript and browsers95.Explain event delegation in JavaScript96.How do you prevent the default behavior of an event?97.What is the difference between event.preventDefault() and event.stopPropagation()?98.What is the difference between mouseenter and mouseover event in JavaScript and browsers?99.What is the difference between innerHTML and textContent?100.How do you manipulate CSS styles using JavaScript?101.Describe the difference between <script>, <script async> and <script defer>102.What is the difference between the Window object and the Document object?103.Describe the difference between a cookie, sessionStorage and localStorage in browsers104.How do you make an HTTP request using the Fetch API?105.What are the different ways to make an API call in JavaScript?106.Explain AJAX in as much detail as possible107.What are the advantages and disadvantages of using AJAX?108.What are the differences between XMLHttpRequest and fetch() in JavaScript and browsers?109.How do you abort a web request using AbortController in JavaScript?110.Explain how JSONP works (and how it's not really Ajax)111.What are workers in JavaScript used for?112.Explain the concept of the Web Socket API113.What are JavaScript polyfills for?114.How do you detect if JavaScript is disabled on a page?115.What is the Intl namespace object for?116.How do you validate form elements using the Constraint Validation API?117.How do you use window.history API?118.How do <iframe> on a page communicate?119.Difference between document load event and document DOMContentLoaded event?120.How do you redirect to a new page in JavaScript?121.How do you get the query string values of the current page in JavaScript?122.What are server-sent events?123.What are Progressive Web Applications (PWAs)?124.What are modules and why are they useful?125.Explain the differences between CommonJS modules and ES modules in JavaScript126.How do you import and export modules in JavaScript?127.What are the benefits of using a module bundler?128.Explain the concept of tree shaking in module bundling129.What are the metadata fields of a module?130.What do you think of CommonJS vs ESM?131.What are the different types of errors in JavaScript?132.How do you handle errors using try...catch blocks?133.What is the purpose of the finally block?134.How can you create custom error objects?135.Explain the concept of error propagation in JavaScript136.What is currying and how does it work?137.Explain the concept of partial application138.What are the benefits of using currying and partial application?139.Provide some examples of how currying and partial application can be used140.How do currying and partial application differ from each other?141.What are Sets and Maps and how are they used?142.What are the differences between Map/Set and WeakMap/WeakSet in JavaScript?143.How do you convert a Set to an array in JavaScript?144.What is the difference between a Map object and a plain object in JavaScript?145.How do Sets and Maps handle equality checks for objects?146.What are some common performance bottlenecks in JavaScript applications?147.Explain the concept of debouncing and throttling148.How can you optimize DOM manipulation for better performance?149.What are some techniques for reducing reflows and repaints?150.Explain the concept of lazy loading and how it can improve performance151.What are Web Workers and how can they be used to improve performance?152.Explain the concept of caching and how it can be used to improve performance153.What are some tools that can be used to measure and analyze JavaScript performance?154.How can you optimize network requests for better performance?155.What are the different types of testing in software development?156.Explain the difference between unit testing, integration testing, and end-to-end testing157.What are some popular JavaScript testing frameworks?158.How do you write unit tests for JavaScript code?159.Explain the concept of test-driven development (TDD)160.What are mocks and stubs and how are they used in testing?161.How can you test asynchronous code in JavaScript?162.What are some best practices for writing maintainable and effective tests in JavaScript?163.Explain the concept of code coverage and how it can be used to assess test quality164.What are some tools that can be used for JavaScript testing?165.What are design patterns and why are they useful?166.Explain the concept of the Singleton pattern167.What is the Factory pattern and how is it used?168.Explain the Observer pattern and its use cases169.What is the Module pattern and how does it help with encapsulation?170.Explain the concept of the Prototype pattern171.What is the Decorator pattern and how is it used?172.Explain the concept of the Strategy pattern173.What is the Command pattern and how is it used?174.Why is extending built-in JavaScript objects not a good idea?175.What is Cross-Site Scripting (XSS) and how can you prevent it?176.Explain the concept of Cross-Site Request Forgery (CSRF) and its mitigation techniques177.How can you prevent SQL injection vulnerabilities in JavaScript applications?178.What are some best practices for handling sensitive data in JavaScript?179.Explain the concept of Content Security Policy (CSP) and how it enhances security180.What are some common security headers and their purpose?181.How can you prevent clickjacking attacks?182.Explain the concept of input validation and its importance in security183.What are some tools and techniques for identifying security vulnerabilities in JavaScript code?184.How can you implement secure authentication and authorization in JavaScript applications?185.Explain the same-origin policy with regards to JavaScript186.What is 'use strict'; in JavaScript for?187.What tools and techniques do you use for debugging JavaScript code?188.How does JavaScript garbage collection work?189.Explain what a single page app is and how to make one SEO-friendly190.How can you share code between JavaScript files?191.How do you organize your code?192.What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?193.When would you use document.write()?
You're viewing a free lesson. Sign up free to track your progress and unlock the full course.Sign up freeSign in