JavaScript and TypeScript Interview Guide for Java Full Stack
Overview
Section titled “Overview”This guide consolidates JavaScript and TypeScript interview topics commonly asked in senior Java Full Stack interviews. It includes explanations, comparisons, examples, and diagrams.
JavaScript Fundamentals
Section titled “JavaScript Fundamentals”What is JavaScript?
Section titled “What is JavaScript?”JavaScript is a:
- High-level language
- Interpreted language
- Prototype-based language
- Dynamically typed language
- Single-threaded language
- Event-driven language
Initially it was created for browsers, but today it also runs on servers using Node.js.
console.log("Hello");Why is JavaScript Single Threaded?
Section titled “Why is JavaScript Single Threaded?”JavaScript has one Call Stack and executes one statement at a time.
flowchart TD A[Task 1] --> B[Task 2] B --> C[Task 3]
Asynchronous work is handled using Browser APIs/Node APIs, queues, and the Event Loop.
Execution Context
Section titled “Execution Context”Execution Context is the environment in which JavaScript code executes.
Two phases:
- Memory Creation Phase
- Execution Phase
flowchart TD A[Execution Context] --> B[Memory Phase] A --> C[Execution Phase] B --> D[Variables initialized] B --> E[Functions stored] C --> F[Execute line by line]
var a = 10;
function test() { console.log(a);}
test();Hoisting
Section titled “Hoisting”Variables and function declarations are hoisted.
console.log(a);var a = 10;Equivalent:
var a;console.log(a);a = 10;Output:
undefinedvar vs let vs const
Section titled “var vs let vs const”| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Redeclare | Yes | No | No |
| Reassign | Yes | Yes | No |
| Hoisted | Yes | Yes | Yes |
| TDZ | No | Yes | Yes |
Temporal Dead Zone
Section titled “Temporal Dead Zone”console.log(a);let a = 10;Produces:
ReferenceErrorClosures
Section titled “Closures”A closure allows an inner function to remember variables from an outer function.
function outer() { let count = 0;
return function () { count++; console.log(count); };}
const fn = outer();fn();fn();fn();Output:
123Uses:
- Data hiding
- Private state
- Memoization
- React Hooks
Lexical Scope
Section titled “Lexical Scope”let x = 10;
function outer() { let x = 20;
function inner() { console.log(x); }
inner();}
outer();Output:
20Event Loop
Section titled “Event Loop”flowchart LR A[Call Stack] --> B[Browser APIs] B --> C[Microtask Queue] B --> D[Macrotask Queue] C --> E[Event Loop] D --> E E --> A
console.log("Start");
setTimeout(() => console.log("Timeout"), 0);
Promise.resolve().then(() => console.log("Promise"));
console.log("End");Output:
StartEndPromiseTimeoutMicrotasks always execute before macrotasks.
Call Stack
Section titled “Call Stack”flowchart TD main --> test test --> display display --> Return
LIFO (Last In, First Out).
Promises
Section titled “Promises”States:
stateDiagram-v2 [*] --> Pending Pending --> Fulfilled Pending --> Rejected
const promise = new Promise((resolve) => { resolve("Success");});
promise.then(console.log);Promise Chaining
Section titled “Promise Chaining”fetch(url) .then(res => res.json()) .then(data => console.log(data)) .catch(console.error);Async/Await
Section titled “Async/Await”async function load() { const response = await fetch(url); const data = await response.json();}Internally uses Promises.
Promise vs Async/Await
Section titled “Promise vs Async/Await”| Promise | Async/Await |
|---|---|
| then/catch | await |
| Chain style | Sequential style |
| Harder to read | Cleaner |
Callback Hell
Section titled “Callback Hell”login(function () { getProfile(function () { getOrders(function () {
}); });});Solved using Promises and async/await.
this Keyword
Section titled “this Keyword”const person = { name: "John", show() { console.log(this.name); }};Arrow functions inherit this lexically.
Arrow Functions
Section titled “Arrow Functions”const add = (a, b) => a + b;Characteristics:
- Lexical this
- No own arguments
- Cannot be constructors
Prototype
Section titled “Prototype”const person = { walk() {}};
const student = Object.create(person);student.walk();Prototype chain:
flowchart TD Student --> Person Person --> Object Object --> Null
Deep Copy
Section titled “Deep Copy”structuredClone(obj);or
JSON.parse(JSON.stringify(obj));== vs ===
Section titled “== vs ===”5 == "5";5 === "5";Results:
truefalseDestructuring
Section titled “Destructuring”const person = { name: "Raj", age: 30 };const { name } = person;Spread Operator
Section titled “Spread Operator”const arr = [1, 2];const newArr = [...arr, 3];Rest Operator
Section titled “Rest Operator”function add(...nums) {}map vs filter vs reduce
Section titled “map vs filter vs reduce”nums.map(x => x * 2);nums.filter(x => x > 5);nums.reduce((a, b) => a + b);forEach vs map
Section titled “forEach vs map”| forEach | map |
|---|---|
| No return | Returns new array |
| No chaining | Supports chaining |
Debouncing
Section titled “Debouncing”let timer;
function debounce(fn) { clearTimeout(timer); timer = setTimeout(fn, 500);}Throttling
Section titled “Throttling”Executes a function at most once during a specified interval.
Useful for scroll, resize, and mousemove events.
function throttle(fn, delay) { let waiting = false; return (...args) => { if (waiting) return; fn(...args); waiting = true; setTimeout(() => waiting = false, delay); };}Event Delegation
Section titled “Event Delegation”parent.addEventListener("click", (e) => {
});Improves performance by attaching one listener to a parent.
Storage
Section titled “Storage”Local Storage vs Session Storage
Section titled “Local Storage vs Session Storage”| Local Storage | Session Storage |
|---|---|
| Persists | Cleared on tab close |
Cookies vs Local Storage
Section titled “Cookies vs Local Storage”Cookies are sent to the server. Local Storage remains in the browser.
Modules
Section titled “Modules”export function add() {}import { add } from "./math.js";Garbage Collection
Section titled “Garbage Collection”JavaScript uses a mark-and-sweep garbage collector.
let user = { name: "Alice" };user = null;Advanced JavaScript
Section titled “Advanced JavaScript”Microtasks vs Macrotasks
Section titled “Microtasks vs Macrotasks”| Microtask | Macrotask |
|---|---|
| Promise.then | setTimeout |
| queueMicrotask | setInterval |
| Higher priority | Lower priority |
Memory Leaks
Section titled “Memory Leaks”Common causes:
- Global variables
- Uncleared timers
- Event listeners
- Closures retaining large objects
Currying
Section titled “Currying”function add(a) { return function (b) { return a + b; };}
console.log(add(5)(10));Function Composition
Section titled “Function Composition”const double = x => x * 2;const square = x => x * x;
console.log(square(double(5)));Performance Optimization
Section titled “Performance Optimization”- Debouncing
- Throttling
- Memoization
- Lazy loading
- Tree shaking
- Code splitting
- Virtual scrolling
- Efficient DOM updates
Prototype vs ES6 Classes
Section titled “Prototype vs ES6 Classes”Prototype:
function Person(name) { this.name = name;}
Person.prototype.sayHi = function () { console.log("Hi");};Class:
class Person { constructor(name) { this.name = name; }
sayHi() { console.log("Hi"); }}Classes are syntactic sugar over prototypes.
Generators
Section titled “Generators”function* numbers() { yield 1; yield 2; yield 3;}
const gen = numbers();
console.log(gen.next());console.log(gen.next());call(), apply(), bind()
Section titled “call(), apply(), bind()”const person = { name: "John" };
function greet(city) { console.log(this.name + " " + city);}
greet.call(person, "London");greet.apply(person, ["London"]);
const fn = greet.bind(person);fn("London");Event Bubbling and Capturing
Section titled “Event Bubbling and Capturing”flowchart TD Body --> Div --> Button
Use:
event.stopPropagation();Optional Chaining and Nullish Coalescing
Section titled “Optional Chaining and Nullish Coalescing”user?.address?.city;
const name = userName ?? "Guest";ES Modules vs CommonJS
Section titled “ES Modules vs CommonJS”| ES Modules | CommonJS |
|---|---|
| import/export | require/module.exports |
| Static | Dynamic |
| Tree shaking | No tree shaking |
TypeScript
Section titled “TypeScript”Why TypeScript?
Section titled “Why TypeScript?”Benefits:
- Static typing
- Interfaces
- Generics
- Compile-time checking
- Better IntelliSense
- Easier refactoring
JavaScript vs TypeScript
Section titled “JavaScript vs TypeScript”| JavaScript | TypeScript |
|---|---|
| Dynamic | Static |
| Runtime errors | Compile-time checking |
| No interfaces | Interfaces |
Basic Types
Section titled “Basic Types”let id: number = 1;let name: string = "Raj";let active: boolean = true;Interfaces
Section titled “Interfaces”interface Employee { id: number; name: string;}Type Alias
Section titled “Type Alias”type Employee = { id: number;};Union Types
Section titled “Union Types”let id: number | string;Intersection Types
Section titled “Intersection Types”type A = { name: string };type B = { age: number };
type Person = A & B;Generics
Section titled “Generics”function identity<T>(value: T): T { return value;}Generic Interface
Section titled “Generic Interface”interface ApiResponse<T> { data: T;}type User = { name: string; age: number;};
type Keys = keyof User;Utility Types
Section titled “Utility Types”- Partial
- Required
- Readonly
- Pick
- Omit
- Record
- Exclude
- Extract
- NonNullable
interface User { id: number; name: string; email?: string;}
type UpdateUser = Partial<User>;type ReadonlyUser = Readonly<User>;type UserSummary = Pick<User, "id" | "name">;type UserWithoutEmail = Omit<User, "email">;enum Status { SUCCESS, FAILED}Decorators
Section titled “Decorators”@Component({ selector: "app-root"})class AppComponent {}unknown vs any
Section titled “unknown vs any”| any | unknown |
|---|---|
| Unsafe | Type-safe |
let value: unknown = "Hello";
if (typeof value === "string") { console.log(value.toUpperCase());}function fail(message: string): never { throw new Error(message);}React + TypeScript
Section titled “React + TypeScript”interface UserProps { name: string; age: number;}
function User({ name, age }: UserProps) { return <h1>{name} - {age}</h1>;}Discriminated Unions
Section titled “Discriminated Unions”type Circle = { kind: "circle"; radius: number;};
type Square = { kind: "square"; side: number;};
type Shape = Circle | Square;
function area(shape: Shape) { if (shape.kind === "circle") { return Math.PI * shape.radius * shape.radius; } return shape.side * shape.side;}Mapped Types
Section titled “Mapped Types”type ReadOnly<T> = { readonly [P in keyof T]: T[P];};Conditional Types
Section titled “Conditional Types”type IsString<T> = T extends string ? true : false;type Return<T> = T extends (...args: any[]) => infer R ? R : never;
function add() { return 10;}
type Result = Return<typeof add>;Generic API Client
Section titled “Generic API Client”interface ApiResponse<T> { data: T; status: number;}
async function get<T>(url: string): Promise<ApiResponse<T>> { const response = await fetch(url); const data = await response.json();
return { data, status: response.status };}Usage:
interface User { id: number; name: string;}
const response = await get<User>("/users/1");console.log(response.data.name);Key Takeaways
Section titled “Key Takeaways”- Master JavaScript fundamentals before advanced concepts.
- Understand the Event Loop, microtasks, closures, and async programming thoroughly.
- Learn prototypes as well as ES6 classes.
- Become comfortable with functional programming concepts such as currying and composition.
- Use TypeScript generics, utility types, discriminated unions, mapped types, and conditional types to write reusable, type-safe applications.
- These topics collectively represent the most common JavaScript and TypeScript interview areas for senior Java Full Stack developers.