JavaScript Interview Questions
Master your interview preparation with comprehensive Q&A covering all difficulty levels
Ace JavaScript Interviews for QA Engineers
Why JavaScript Knowledge is Critical: Modern testing tools (Cypress, Playwright, WebdriverIO) are built in JavaScript. If you're interviewing at a company using these tools, JavaScript knowledge is non-negotiable. Interviewers expect understanding of async/await, promises, and DOM manipulation.
Core Topics Interviewers Focus On:
- Async/Await & Promises: Essential for writing reliable E2E tests with Cypress
- DOM Manipulation: How browsers work, querySelector, events
- Closures & Scope: Understanding variable scope prevents test data leakage
- Array Methods: filter(), map(), reduce() — used for test data processing
- Fetch API: Making HTTP requests for API testing
- Error Handling: try-catch, proper error messages in test failures
What Differentiates Strong Candidates: Understanding why Cypress chose JavaScript (direct DOM access in browser), not just knowing the syntax. Explain async/await not as "async functions" but as "how we wait for actions to complete in tests."
Avoid These Mistakes:
- ❌ Confusing == with === (always use === in tests)
- ❌ Not understanding event loop and how async code executes
- ❌ Assuming all arrays are the same (sparse arrays, array-like objects)
- ❌ Not mentioning Cypress or Playwright when discussing E2E testing
JavaScript Interview Questions - Beginner Level
What is JavaScript?
JavaScript is a lightweight, interpreted programming language primarily used for web development. Runs in browsers and Node.js. Dynamic typing, supports OOP and functional programming.
What are variables and how do you declare them?
Variables store values. Declare with var, let, or const. Example: var x = 5; let y = 10; const z = 15;
What is the difference between var, let, and const?
var is function-scoped, let/const are block-scoped. var can be redeclared, let cannot. const is immutable (cannot be reassigned).
What are data types in JavaScript?
Primitive: string, number, boolean, null, undefined, symbol. Object: object (includes arrays, functions). Dynamically typed language.
What is typeof operator?
Returns data type: typeof 5 returns "number". typeof "hello" returns "string". typeof {} returns "object".
What is NaN and how do you check for it?
NaN (Not a Number) is special value. Check: Number.isNaN(value) or isNaN(value). Example: 0/0 returns NaN.
What is hoisting?
Variables and function declarations moved to top of scope before execution. var initialized as undefined, let/const not initialized (temporal dead zone).
What are functions in JavaScript?
Reusable blocks of code. Declare: function name(params) { } or const name = (params) => { } (arrow function).
What is a callback function?
Function passed as argument to another function, called later. Example: setTimeout(callback, 1000);
What is a closure?
Function with access to variables from outer scope even after outer function returns. Example: function outer() { let x = 1; return function() { return x; } }
What is scope in JavaScript?
Visibility of variables. Global scope (window object), function scope, block scope. Inner scope can access outer scope.
What is this keyword?
References current object. In functions, refers to window (non-strict) or undefined (strict). In methods, refers to object.
What are arrow functions?
Concise syntax: const sum = (a, b) => a + b; Don't have their own this, inherit from parent scope.
What are events in JavaScript?
User interactions: click, submit, change, keydown, mouseover. Handle with addEventListener or onclick attribute.
What is event delegation?
Attaching listener to parent element to handle events from child elements. Improves performance.
What is DOM (Document Object Model)?
Tree representation of HTML. JavaScript accesses/modifies DOM. Root: document object. Example: document.getElementById('id').innerHTML
How do you select elements?
document.getElementById('id'), document.querySelector('selector'), document.querySelectorAll('selector'), document.getElementsByClassName('class')
How do you modify element content?
element.innerHTML = "text" (parses HTML). element.textContent = "text" (plain text). element.innerText (visible text).
How do you modify element attributes?
element.setAttribute('attr', 'value'). element.getAttribute('attr'). element.removeAttribute('attr').
How do you modify element classes?
element.classList.add('class'), .remove('class'), .toggle('class'), .contains('class').
What are Promises?
Handle asynchronous operations. States: pending, resolved, rejected. Example: new Promise((resolve, reject) => {})
What is async/await?
Syntactic sugar for Promises. async function returns Promise. await pauses execution until Promise resolves.
What is JSON?
JavaScript Object Notation. Text format for data interchange. Parse: JSON.parse(string). Stringify: JSON.stringify(object).
What is fetch API?
Modern way to make HTTP requests. fetch(url).then(response => response.json()).then(data => {})
What is XMLHttpRequest (XHR)?
Older API for HTTP requests. Create: const xhr = new XMLHttpRequest(); Replaced by fetch API.
What are arrays in JavaScript?
Ordered collection of values. Declare: const arr = [1, 2, 3] or new Array(). Dynamic size.
What are array methods?
push(), pop(), shift(), unshift(), map(), filter(), reduce(), forEach(), find(), includes(), indexOf(), slice(), splice().
What is an object in JavaScript?
Collection of key-value pairs. Declare: const obj = { name: "John", age: 30 } or new Object(). Access: obj.name or obj["name"].
What is destructuring?
Extract values from object/array into variables. Example: const { name, age } = obj; or const [a, b] = arr;
What is spread operator?
... spreads array/object. Example: const arr2 = [...arr1, 4, 5]; or const obj2 = { ...obj1, prop: value }
What is rest parameter?
... collects arguments. Example: function sum(...numbers) { return numbers.reduce((a, b) => a + b); }
What is default parameter?
Provide default value if argument not passed. Example: function greet(name = "Guest") { }
What are template literals?
Backtick strings with interpolation. Example: `Hello ${name}` instead of "Hello " + name
What is strict mode?
Enforce stricter parsing and error checking. Enable: "use strict"; at top of file or function.
What is null vs undefined?
null is intentionally no value. undefined is variable declared but not assigned. typeof null returns "object" (bug).
What is truthy and falsy?
Falsy: false, 0, "", null, undefined, NaN. Truthy: everything else. Used in conditions: if (value) { }
What are comparison operators?
==, ===, !=, !==, <, >, <=, >=. === checks type and value, == only value.
What are logical operators?
&&, ||, !. Example: if (a && b) { } or (a || b)
What is optional chaining (?.) ?
Safely access deeply nested properties. Example: obj?.prop?.subProp returns undefined if null.
What is nullish coalescing (??)?
Returns right operand if left is null/undefined. Example: value ?? "default" returns "default" if value is null.
What are regular expressions?
Pattern matching. Create: /pattern/flags or new RegExp("pattern", "flags"). Methods: test(), exec(), match(), replace().
What are string methods?
length, charAt(), substring(), slice(), indexOf(), split(), toUpperCase(), toLowerCase(), trim(), replace().
What is the window object?
Global object in browsers. Contains alert(), setTimeout(), setInterval(), fetch(), document, etc.
What is localStorage?
Stores data in browser (persistent). localStorage.setItem('key', 'value'), getItem(), removeItem().
What is sessionStorage?
Stores data per browser session (cleared on close). Similar API to localStorage.
What are cookies?
Store small data in browser. Set: document.cookie = "name=value"; Get: document.cookie returns all cookies.
What is console object?
Debugging tool. Methods: console.log(), console.error(), console.warn(), console.table(), console.time().
What is error handling?
try-catch-finally. Example: try { } catch (error) { } finally { }
What are custom errors?
Create custom error classes: class MyError extends Error { }
What is the purpose of isNaN() and Number.isNaN()?
isNaN() converts to number first (loose check). Number.isNaN() checks if NaN (strict). Prefer Number.isNaN().
JavaScript Interview Questions - Intermediate Level
What is prototypal inheritance?
Objects inherit from prototype. Prototype chain: object.__proto__. Every function has prototype property.
What is the prototype property?
Each function has prototype object. Instances inherit from prototype: obj.__proto__ === constructor.prototype
What is a constructor function?
Function called with new keyword to create object. Example: function Person(name) { this.name = name; } const p = new Person("John");
What is the new keyword?
Creates new object, sets prototype, calls constructor, returns object.
What are classes in JavaScript (ES6)?
Syntactic sugar for constructor functions. Example: class Person { constructor(name) { this.name = name; } }
What are getters and setters?
get/set keywords. Example: get name() { return this._name; } set name(value) { this._name = value; }
What is static methods?
Methods on class, not instance. Example: class Math { static add(a, b) { return a + b; } } Math.add(1, 2);
What is inheritance in ES6 classes?
Use extends and super. Example: class Dog extends Animal { constructor(name) { super(name); } }
What are Symbols?
Primitive type representing unique identifier. Example: const sym = Symbol('desc'); Cannot be accessed with for...in.
What is the Object.create() method?
Creates object with specified prototype. Example: const obj = Object.create(proto);
What are property descriptors?
Define properties precisely: Object.defineProperty(obj, 'prop', { value: 5, writable: false, enumerable: true });
What is Object.freeze() and Object.seal()?
freeze prevents modification. seal allows modification but not adding/removing properties.
What is event bubbling?
Event propagates from target to parent elements. Stop with event.stopPropagation().
What is event capturing?
Event propagates from parent to target. addEventListener(..., true) enables capturing phase.
What is debouncing?
Execute function after delay. Useful for search input: function debounce(fn, delay) { let timer; return function() { clearTimeout(timer); timer = setTimeout(fn, delay); } }
What is throttling?
Execute function at most once per interval. Useful for scroll/resize: function throttle(fn, delay) { let last = 0; return function() { const now = Date.now(); if (now - last >= delay) { fn(); last = now; } } }
What is memoization?
Cache function results. Example: function memoize(fn) { const cache = {}; return function(arg) { if (arg in cache) return cache[arg]; return cache[arg] = fn(arg); } }
What is currying?
Convert function to chain of single-argument functions. Example: const add = (a) => (b) => a + b; add(1)(2)
What is partial application?
Fix some arguments of function. Example: const add5 = add.bind(null, 5); add5(3)
What is higher-order function?
Function that takes/returns function. Example: function twice(fn) { return function() { fn(); fn(); } }
What are generators?
Functions that can pause/resume. Use function* and yield. Example: function* gen() { yield 1; yield 2; }
What is async iteration?
Iterate over async values. Use for await...of. Example: for await (const value of asyncIterable) { }
What is the event loop?
JavaScript runs synchronously. Callbacks go to task queue. Event loop executes when main thread is empty.
What is the microtask queue?
Higher priority than task queue. Promises, async/await use microtask queue. Executes after main code, before task queue.
What is setTimeout vs setInterval?
setTimeout executes once after delay. setInterval executes repeatedly. Example: setTimeout(fn, 1000); setInterval(fn, 1000);
What is the call() method?
Invoke function with specific this. Example: function.call(thisArg, arg1, arg2);
What is the apply() method?
Similar to call() but takes array of arguments. Example: function.apply(thisArg, [arg1, arg2]);
What is the bind() method?
Creates new function with specified this. Example: const boundFn = function.bind(thisArg);
What is the Map object?
Key-value collection. Keys can be any type (unlike objects). new Map(); map.set(key, value); map.get(key);
What is the Set object?
Collection of unique values. new Set(); set.add(value); set.has(value);
What are WeakMap and WeakSet?
Similar to Map/Set but hold weak references. Garbage collected if no other references. Keys must be objects.
What is Proxy?
Intercept and customize operations on objects. Example: const proxy = new Proxy(target, handler);
What is Reflect API?
Provides methods for interceptable operations. Example: Reflect.get(obj, 'prop'); Reflect.set(obj, 'prop', value);
What are modules (import/export)?
Organize code into reusable pieces. export const func = () => {}; import { func } from "./module";
What is circular dependency?
Module A depends on B, B depends on A. Causes issues. Avoid by restructuring modules.
What is window.location?
Access/modify URL. window.location.href, .pathname, .search, .hash, .reload(), .replace().
What is window.history?
Manage browser history. history.back(), .forward(), .go(n).
What is the Intersection Observer API?
Detect when elements enter viewport. Useful for lazy loading: new IntersectionObserver(callback);
What is the MutationObserver API?
Watch for DOM changes. Example: new MutationObserver(callback).observe(element, options);
What are Web Workers?
Run JavaScript in background thread. Prevent blocking main thread. new Worker('worker.js');
What is TypeScript?
Superset of JavaScript with static typing. Compiled to JavaScript. Example: const x: number = 5;
What are interfaces in TypeScript?
Define object structure. Example: interface User { name: string; age: number; }
What are types in TypeScript?
Define data structure. Example: type User = { name: string; age: number; }
What are generics in TypeScript?
Type parameters for reusable code. Example: function identity<T>(arg: T): T { return arg; }
What is the as keyword (type casting)?
Assert type explicitly. Example: (value as string).toUpperCase();
What are union types?
Variable can be one of multiple types. Example: type Status = "active" | "inactive";
What are intersection types?
Combine multiple types. Example: type Admin = User & { adminId: number; }
What is the readonly keyword?
Make properties immutable. Example: interface User { readonly id: number; }
What are enums?
Define set of constants. Example: enum Color { Red = 0, Green = 1, Blue = 2 }
What is a type guard?
Narrow type in conditional block. Example: if (typeof value === "string") { ... }
JavaScript Interview Questions - Advanced Level
What is AST (Abstract Syntax Tree)?
Tree representation of code structure. Used by compilers and linters. Example: ESLint, Babel use AST.
What is hoisting in detail?
Variable/function declarations moved to scope top. var hoisted as undefined. Function declarations fully hoisted. let/const not hoisted (temporal dead zone).
What is JavaScript engine (V8, SpiderMonkey)?
Interprets/compiles JavaScript. V8 (Chrome), SpiderMonkey (Firefox), JavaScriptCore (Safari). Uses JIT compilation.
What is performance optimization?
Minimize DOM operations, use debouncing/throttling, lazy load, code splitting, caching, use efficient algorithms.
105-150. Advanced Topics (abbreviated)
105-110: Code splitting, tree shaking, bundlers (Webpack, Rollup, Vite), transpilation (Babel), module federation. 111-115: Testing frameworks (Jest, Mocha, Jasmine), mocking, test doubles, coverage analysis, CI/CD integration. 116-120: Design patterns (Observer, Factory, Singleton, Strategy), SOLID principles, OWASP security. 121-125: DOM optimization, virtual DOM (React), rendering engines, layout/paint optimization, memory leaks. 126-130: Frameworks (React, Vue, Angular), state management (Redux, Zustand), reactive programming (RxJS). 131-135: Progressive Web Apps (PWA), Service Workers, Indexed DB, Web APIs, Fetch API advanced. 136-140: Node.js, Express, file system, streams, child processes, worker threads. 141-145: GraphQL clients, REST client libraries, WebSocket implementation, real-time communication. 146-150: Security (XSS prevention, CSRF protection, Content Security Policy), performance monitoring, error tracking, analytics integration.