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

Q 1

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.

JavaScriptlightweightinterpretedprogramming
Q 2

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;

VariablesstorevaluesDeclare
Q 3

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).

function-scopedlet/constblock-scopedredeclared
Q 4

What are data types in JavaScript?

Primitive: string, number, boolean, null, undefined, symbol. Object: object (includes arrays, functions). Dynamically typed language.

Primitivestringnumberboolean
Q 5

What is typeof operator?

Returns data type: typeof 5 returns "number". typeof "hello" returns "string". typeof {} returns "object".

Returnsdatatypetypeof
Q 6

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.

(NotNumber)specialvalue
Q 7

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).

Variablesfunctiondeclarationsmoved
Q 8

What are functions in JavaScript?

Reusable blocks of code. Declare: function name(params) { } or const name = (params) => { } (arrow function).

ReusableblockscodeDeclare
Q 9

What is a callback function?

Function passed as argument to another function, called later. Example: setTimeout(callback, 1000);

Functionpassedargumentanother
Q 10

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; } }

Functionaccessvariablesouter
Q 11

What is scope in JavaScript?

Visibility of variables. Global scope (window object), function scope, block scope. Inner scope can access outer scope.

VisibilityvariablesGlobalscope
Q 12

What is this keyword?

References current object. In functions, refers to window (non-strict) or undefined (strict). In methods, refers to object.

Referencescurrentobjectfunctions
Q 13

What are arrow functions?

Concise syntax: const sum = (a, b) => a + b; Don't have their own this, inherit from parent scope.

ConcisesyntaxconstDon't
Q 14

What are events in JavaScript?

User interactions: click, submit, change, keydown, mouseover. Handle with addEventListener or onclick attribute.

Userinteractionsclicksubmit
Q 15

What is event delegation?

Attaching listener to parent element to handle events from child elements. Improves performance.

Attachinglistenerparentelement
Q 16

What is DOM (Document Object Model)?

Tree representation of HTML. JavaScript accesses/modifies DOM. Root: document object. Example: document.getElementById('id').innerHTML

TreerepresentationHTMLJavaScript
Q 17

How do you select elements?

document.getElementById('id'), document.querySelector('selector'), document.querySelectorAll('selector'), document.getElementsByClassName('class')

documentgetElementById('id')documentquerySelector('selec
Q 18

How do you modify element content?

element.innerHTML = "text" (parses HTML). element.textContent = "text" (plain text). element.innerText (visible text).

elementinnerHTML"text"(parses
Q 19

How do you modify element attributes?

element.setAttribute('attr', 'value'). element.getAttribute('attr'). element.removeAttribute('attr').

elementsetAttribute('attr''value')element
Q 20

How do you modify element classes?

element.classList.add('class'), .remove('class'), .toggle('class'), .contains('class').

elementclassListadd('class')remove('class')
Q 21

What are Promises?

Handle asynchronous operations. States: pending, resolved, rejected. Example: new Promise((resolve, reject) => {})

HandleasynchronousoperationsStates
Q 22

What is async/await?

Syntactic sugar for Promises. async function returns Promise. await pauses execution until Promise resolves.

SyntacticsugarPromisesasync
Q 23

What is JSON?

JavaScript Object Notation. Text format for data interchange. Parse: JSON.parse(string). Stringify: JSON.stringify(object).

JavaScriptObjectNotationText
Q 24

What is fetch API?

Modern way to make HTTP requests. fetch(url).then(response => response.json()).then(data => {})

ModernmakeHTTPrequests
Q 25

What is XMLHttpRequest (XHR)?

Older API for HTTP requests. Create: const xhr = new XMLHttpRequest(); Replaced by fetch API.

OlderHTTPrequestsCreate
Q 26

What are arrays in JavaScript?

Ordered collection of values. Declare: const arr = [1, 2, 3] or new Array(). Dynamic size.

OrderedcollectionvaluesDeclare
Q 27

What are array methods?

push(), pop(), shift(), unshift(), map(), filter(), reduce(), forEach(), find(), includes(), indexOf(), slice(), splice().

push()pop()shift()unshift()
Q 28

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"].

Collectionkey-valuepairsDeclare
Q 29

What is destructuring?

Extract values from object/array into variables. Example: const { name, age } = obj; or const [a, b] = arr;

Extractvaluesobject/arrayinto
Q 30

What is spread operator?

... spreads array/object. Example: const arr2 = [...arr1, 4, 5]; or const obj2 = { ...obj1, prop: value }

spreadsarray/objectExampleconst
Q 31

What is rest parameter?

... collects arguments. Example: function sum(...numbers) { return numbers.reduce((a, b) => a + b); }

collectsargumentsExamplefunction
Q 32

What is default parameter?

Provide default value if argument not passed. Example: function greet(name = "Guest") { }

Providedefaultvalueargument
Q 33

What are template literals?

Backtick strings with interpolation. Example: `Hello ${name}` instead of "Hello " + name

BacktickstringsinterpolationExample
Q 34

What is strict mode?

Enforce stricter parsing and error checking. Enable: "use strict"; at top of file or function.

Enforcestricterparsingerror
Q 35

What is null vs undefined?

null is intentionally no value. undefined is variable declared but not assigned. typeof null returns "object" (bug).

nullintentionallyvalueundefined
Q 36

What is truthy and falsy?

Falsy: false, 0, "", null, undefined, NaN. Truthy: everything else. Used in conditions: if (value) { }

Falsyfalsenullundefined
Q 37

What are comparison operators?

==, ===, !=, !==, <, >, <=, >=. === checks type and value, == only value.

checkstypevalueonly
Q 38

What are logical operators?

&&, ||, !. Example: if (a && b) { } or (a || b)

Example
Q 39

What is optional chaining (?.) ?

Safely access deeply nested properties. Example: obj?.prop?.subProp returns undefined if null.

Safelyaccessdeeplynested
Q 40

What is nullish coalescing (??)?

Returns right operand if left is null/undefined. Example: value ?? "default" returns "default" if value is null.

Returnsrightoperandleft
Q 41

What are regular expressions?

Pattern matching. Create: /pattern/flags or new RegExp("pattern", "flags"). Methods: test(), exec(), match(), replace().

PatternmatchingCreate/pattern/flags
Q 42

What are string methods?

length, charAt(), substring(), slice(), indexOf(), split(), toUpperCase(), toLowerCase(), trim(), replace().

lengthcharAt()substring()slice()
Q 43

What is the window object?

Global object in browsers. Contains alert(), setTimeout(), setInterval(), fetch(), document, etc.

GlobalobjectbrowsersContains
Q 44

What is localStorage?

Stores data in browser (persistent). localStorage.setItem('key', 'value'), getItem(), removeItem().

Storesdatabrowser(persistent)
Q 45

What is sessionStorage?

Stores data per browser session (cleared on close). Similar API to localStorage.

Storesdatabrowsersession
Q 46

What are cookies?

Store small data in browser. Set: document.cookie = "name=value"; Get: document.cookie returns all cookies.

Storesmalldatabrowser
Q 47

What is console object?

Debugging tool. Methods: console.log(), console.error(), console.warn(), console.table(), console.time().

DebuggingtoolMethodsconsole
Q 48

What is error handling?

try-catch-finally. Example: try { } catch (error) { } finally { }

try-catch-finallyExamplecatch(error)
Q 49

What are custom errors?

Create custom error classes: class MyError extends Error { }

Createcustomerrorclasses
Q 50

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().

isNaN()convertsnumberfirst

JavaScript Interview Questions - Intermediate Level

Q 51

What is prototypal inheritance?

Objects inherit from prototype. Prototype chain: object.__proto__. Every function has prototype property.

ObjectsinheritprototypePrototype
Q 52

What is the prototype property?

Each function has prototype object. Instances inherit from prototype: obj.__proto__ === constructor.prototype

Eachfunctionprototypeobject
Q 53

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");

Functioncalledkeywordcreate
Q 54

What is the new keyword?

Creates new object, sets prototype, calls constructor, returns object.

Createsobjectsetsprototype
Q 55

What are classes in JavaScript (ES6)?

Syntactic sugar for constructor functions. Example: class Person { constructor(name) { this.name = name; } }

Syntacticsugarconstructorfunctions
Q 56

What are getters and setters?

get/set keywords. Example: get name() { return this._name; } set name(value) { this._name = value; }

get/setkeywordsExamplename()
Q 57

What is static methods?

Methods on class, not instance. Example: class Math { static add(a, b) { return a + b; } } Math.add(1, 2);

MethodsclassinstanceExample
Q 58

What is inheritance in ES6 classes?

Use extends and super. Example: class Dog extends Animal { constructor(name) { super(name); } }

extendssuperExampleclass
Q 59

What are Symbols?

Primitive type representing unique identifier. Example: const sym = Symbol('desc'); Cannot be accessed with for...in.

Primitivetyperepresentingunique
Q 60

What is the Object.create() method?

Creates object with specified prototype. Example: const obj = Object.create(proto);

Createsobjectspecifiedprototype
Q 61

What are property descriptors?

Define properties precisely: Object.defineProperty(obj, 'prop', { value: 5, writable: false, enumerable: true });

DefinepropertiespreciselyObject
Q 62

What is Object.freeze() and Object.seal()?

freeze prevents modification. seal allows modification but not adding/removing properties.

freezepreventsmodificationseal
Q 63

What is event bubbling?

Event propagates from target to parent elements. Stop with event.stopPropagation().

Eventpropagatestargetparent
Q 64

What is event capturing?

Event propagates from parent to target. addEventListener(..., true) enables capturing phase.

Eventpropagatesparenttarget
Q 65

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); } }

Executefunctionafterdelay
Q 66

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; } } }

Executefunctionmostonce
Q 67

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); } }

CachefunctionresultsExample
Q 68

What is currying?

Convert function to chain of single-argument functions. Example: const add = (a) => (b) => a + b; add(1)(2)

Convertfunctionchainsingle-argument
Q 69

What is partial application?

Fix some arguments of function. Example: const add5 = add.bind(null, 5); add5(3)

someargumentsfunctionExample
Q 70

What is higher-order function?

Function that takes/returns function. Example: function twice(fn) { return function() { fn(); fn(); } }

Functiontakes/returnsfunctionExample
Q 71

What are generators?

Functions that can pause/resume. Use function* and yield. Example: function* gen() { yield 1; yield 2; }

Functionspause/resumefunction*yield
Q 72

What is async iteration?

Iterate over async values. Use for await...of. Example: for await (const value of asyncIterable) { }

Iterateoverasyncvalues
Q 73

What is the event loop?

JavaScript runs synchronously. Callbacks go to task queue. Event loop executes when main thread is empty.

JavaScriptrunssynchronouslyCallbacks
Q 74

What is the microtask queue?

Higher priority than task queue. Promises, async/await use microtask queue. Executes after main code, before task queue.

Higherprioritythantask
Q 75

What is setTimeout vs setInterval?

setTimeout executes once after delay. setInterval executes repeatedly. Example: setTimeout(fn, 1000); setInterval(fn, 1000);

setTimeoutexecutesonceafter
Q 76

What is the call() method?

Invoke function with specific this. Example: function.call(thisArg, arg1, arg2);

InvokefunctionspecificExample
Q 77

What is the apply() method?

Similar to call() but takes array of arguments. Example: function.apply(thisArg, [arg1, arg2]);

Similarcall()takesarray
Q 78

What is the bind() method?

Creates new function with specified this. Example: const boundFn = function.bind(thisArg);

CreatesfunctionspecifiedExample
Q 79

What is the Map object?

Key-value collection. Keys can be any type (unlike objects). new Map(); map.set(key, value); map.get(key);

Key-valuecollectionKeystype
Q 80

What is the Set object?

Collection of unique values. new Set(); set.add(value); set.has(value);

CollectionuniquevaluesSet()
Q 81

What are WeakMap and WeakSet?

Similar to Map/Set but hold weak references. Garbage collected if no other references. Keys must be objects.

SimilarMap/Setholdweak
Q 82

What is Proxy?

Intercept and customize operations on objects. Example: const proxy = new Proxy(target, handler);

Interceptcustomizeoperationsobjects
Q 83

What is Reflect API?

Provides methods for interceptable operations. Example: Reflect.get(obj, 'prop'); Reflect.set(obj, 'prop', value);

Providesmethodsinterceptableoperations
Q 84

What are modules (import/export)?

Organize code into reusable pieces. export const func = () => {}; import { func } from "./module";

Organizecodeintoreusable
Q 85

What is circular dependency?

Module A depends on B, B depends on A. Causes issues. Avoid by restructuring modules.

ModuledependsdependsCauses
Q 86

What is window.location?

Access/modify URL. window.location.href, .pathname, .search, .hash, .reload(), .replace().

Access/modifywindowlocationhref
Q 87

What is window.history?

Manage browser history. history.back(), .forward(), .go(n).

Managebrowserhistoryhistory
Q 88

What is the Intersection Observer API?

Detect when elements enter viewport. Useful for lazy loading: new IntersectionObserver(callback);

Detectwhenelementsenter
Q 89

What is the MutationObserver API?

Watch for DOM changes. Example: new MutationObserver(callback).observe(element, options);

WatchchangesExampleMutationObserver(cal
Q 90

What are Web Workers?

Run JavaScript in background thread. Prevent blocking main thread. new Worker('worker.js');

JavaScriptbackgroundthreadPrevent
Q 91

What is TypeScript?

Superset of JavaScript with static typing. Compiled to JavaScript. Example: const x: number = 5;

SupersetJavaScriptstatictyping
Q 92

What are interfaces in TypeScript?

Define object structure. Example: interface User { name: string; age: number; }

DefineobjectstructureExample
Q 93

What are types in TypeScript?

Define data structure. Example: type User = { name: string; age: number; }

DefinedatastructureExample
Q 94

What are generics in TypeScript?

Type parameters for reusable code. Example: function identity<T>(arg: T): T { return arg; }

Typeparametersreusablecode
Q 95

What is the as keyword (type casting)?

Assert type explicitly. Example: (value as string).toUpperCase();

AsserttypeexplicitlyExample
Q 96

What are union types?

Variable can be one of multiple types. Example: type Status = "active" | "inactive";

VariablemultipletypesExample
Q 97

What are intersection types?

Combine multiple types. Example: type Admin = User & { adminId: number; }

CombinemultipletypesExample
Q 98

What is the readonly keyword?

Make properties immutable. Example: interface User { readonly id: number; }

MakepropertiesimmutableExample
Q 99

What are enums?

Define set of constants. Example: enum Color { Red = 0, Green = 1, Blue = 2 }

DefineconstantsExampleenum
Q 100

What is a type guard?

Narrow type in conditional block. Example: if (typeof value === "string") { ... }

Narrowtypeconditionalblock

JavaScript Interview Questions - Advanced Level

Q 101

What is AST (Abstract Syntax Tree)?

Tree representation of code structure. Used by compilers and linters. Example: ESLint, Babel use AST.

Treerepresentationcodestructure
Q 102

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).

Variable/functiondeclarationsmovedscope
Q 103

What is JavaScript engine (V8, SpiderMonkey)?

Interprets/compiles JavaScript. V8 (Chrome), SpiderMonkey (Firefox), JavaScriptCore (Safari). Uses JIT compilation.

Interprets/compilesJavaScript(Chrome)SpiderMonkey
Q 104

What is performance optimization?

Minimize DOM operations, use debouncing/throttling, lazy load, code splitting, caching, use efficient algorithms.

Minimizeoperationsdebouncing/throttlinlazy

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.