JavaScript Interview Questions and Answers
(Detailed)
What is JavaScript and how does it differ from HTML and CSS?
JavaScript is a programming language used to make web pages interactive. HTML defines the
structure of a page, CSS handles styling, and JavaScript adds behavior. Example: creating pop-up
alerts or form validation.
What are variables in JavaScript? How do you declare them (var,
let, const)? Differences?
Variables store data. `var` is function-scoped, `let` and `const` are block-scoped. `const` cannot be
reassigned, `let` can, `var` can be redeclared. Example: let name = 'John'; const age = 30; var city
= 'NY';
Explain data types in JavaScript.
Primitive: string, number, boolean, null, undefined, symbol, bigint. Non-primitive: objects. Example:
let name = 'Alice'; let age = 25; let active = true;
What are arrays and how do you use them?
Arrays store ordered collections of values. Example: let fruits = ['apple','banana','orange'];
[Link](fruits[0]);
What is an object? Give an example.
Objects store key-value pairs. Example: let person = {name: 'John', age: 30};
[Link]([Link]);
What are functions and how do you define/call them?
Functions group reusable code. Example: function greet(name) { return `Hello ${name}`; }
[Link](greet('Alice'));
Difference between function declaration and expression.
Declaration is hoisted: function add(a,b){ return a+b; }. Expression is not: const add = function(a,b){
return a+b; };
What are arrow functions? Differences from normal functions.
Short syntax, no own `this` binding. Example: const sum = (a,b) => a+b;
What is scope? Local vs global?
Scope determines variable accessibility. Global: accessible anywhere. Local: accessible only in
function/block. Example: let x=10; function test(){ let y=5; }
Explain hoisting.
JS moves declarations to top of scope. Functions and `var` are hoisted; `let` and `const` are not.
What is closure? Example.
A closure retains access to parent variables: function outer(){ let count=0; return function(){
count++; return count; } } const counter=outer(); counter(); //1
What is DOM? How to interact?
Document Object Model represents HTML as objects. Use JS to read/modify elements. Example:
[Link]('demo').innerText='Hello';
How to select DOM elements?
Methods: getElementById, getElementsByClassName, querySelector, querySelectorAll.
How to add event listeners?
[Link]('click', () => { alert('Clicked'); });
What are callback functions?
Functions passed as arguments to execute later. Example: setTimeout(() => [Link]('Hello'),
1000);
What are Promises?
Handle async operations. States: pending, fulfilled, rejected. Example: fetch(url).then(res =>
[Link]()).catch(err => [Link](err));
Explain async/await.
Syntax to handle Promises more readably. Example: async function fetchData(){ let res=await
fetch(url); let data=await [Link](); }
What is fetch API?
Modern way to make HTTP requests returning a Promise.
Difference between synchronous and asynchronous code.
Synchronous blocks execution; asynchronous allows non-blocking operations.
What are higher-order functions?
Functions taking or returning other functions. Example: const nums=[1,2,3]; [Link](x=>x*2);
What is map, filter, reduce?
map transforms, filter filters, reduce aggregates arrays.
What are template literals?
Strings with backticks supporting interpolation: `Hello ${name}`
Spread and rest operators?
`...` spreads elements or collects arguments. Example: const arr2=[...arr,3]; function sum(...args){
return [Link]((a,b)=>a+b); }
Object/array destructuring?
Extract values into variables: const {name}=person; const [a,b]=arr;
Modules? Import/export?
Reusable code files: export const pi=3.14; import {pi} from './[Link]';
Event propagation (bubbling/capturing)?
Bubbling: child → parent. Capturing: parent → child. Controlled via third argument in
addEventListener.
What is this?
Refers to the object owning the executing code. Depends on call context.
Handle errors (try/catch/finally)?
try { riskyCode(); } catch(err){ [Link](err); } finally{ cleanup(); }
Event loop?
JS executes tasks via call stack and message queue, handling async operations without blocking.
Microtasks vs macrotasks?
Microtasks: Promises. Macrotasks: setTimeout/setInterval. Microtasks run first after current stack
clears.
Debounce/throttle functions?
Debounce delays execution until idle; throttle limits frequency.
Closure memory leak?
Closures retain references; if not cleaned, can cause memory leaks.
Manage state in vanilla JS?
Use objects/arrays, update DOM manually or via frameworks/libraries.
Prototype inheritance?
Objects inherit from prototypes. Example: function Person(){ [Link]='Alice'; }
[Link]=function(){[Link]([Link]);}
Class vs prototype?
Class syntax is sugar over prototype inheritance: class Person { constructor(name){
[Link]=name; } greet(){ [Link]([Link]); } }
Optimize JS performance?
Minimize DOM access, caching, debounce events, lazy load, avoid heavy loops.
Module bundler?
Combine multiple JS files into one for browsers (Webpack, Rollup). Manual example: concatenating
files and resolving imports.
Cross-browser compatibility?
Use polyfills, transpilers (Babel), test on multiple browsers.
Testing JS code?
Unit testing frameworks: Jest, Mocha, Jasmine. Example: expect(sum(2,3)).toBe(5);
Design a small interactive feature?
Example: To-do list: HTML input+button+list, JS add/remove items, update DOM, store in
localStorage for persistence.