0% found this document useful (0 votes)
9 views16 pages

JS Interview Prep Top20

This document is a comprehensive guide for JavaScript interview preparation, covering 20 core concepts including closures, prototypes, async/await, and ES6+ features. It provides clear explanations and practical code examples for each concept, making it suitable for mastering JavaScript fundamentals. The content is structured into sections such as Foundations, Objects & Prototypes, Asynchronous JavaScript, and Advanced Concepts.

Uploaded by

dipakpatil200412
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views16 pages

JS Interview Prep Top20

This document is a comprehensive guide for JavaScript interview preparation, covering 20 core concepts including closures, prototypes, async/await, and ES6+ features. It provides clear explanations and practical code examples for each concept, making it suitable for mastering JavaScript fundamentals. The content is structured into sections such as Foundations, Objects & Prototypes, Asynchronous JavaScript, and Advanced Concepts.

Uploaded by

dipakpatil200412
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript Interview Prep

Top 20 Concepts & Practicals

■ 20 Core Concepts ■ Practical Code Examples ■ Interview Ready

A comprehensive guide to mastering JavaScript fundamentals for technical interviews. Covers


closures, prototypes, async/await, event loop, ES6+ features, and more — with clear
explanations and practical code examples for each concept.

[Link]
Table of Contents
FOUNDATIONS
01 var, let & const — Scoping & Hoisting

02 Data Types & Type Coercion

03 Functions: Declarations, Expressions & Arrow Functions

04 Scope & Closures

05 The 'this' Keyword

OBJECTS & PROTOTYPES


06 Prototypes & Prototype Chain

07 Object Methods: call, apply & bind

08 Destructuring & Spread / Rest Operators

09 Classes & Inheritance (ES6+)

ASYNCHRONOUS JAVASCRIPT
10 Callbacks & Callback Hell

11 Promises

12 async / await

13 The Event Loop & Call Stack

ARRAYS & ITERATION


14 Array Methods: map, filter, reduce

15 for...of vs for...in

ADVANCED CONCEPTS
16 Event Delegation & Bubbling

17 Debouncing & Throttling

18 Modules (ES Modules & CommonJS)

19 Memoization & Pure Functions

20 Error Handling & try/catch/finally

JavaScript Interview Prep — Top 20 Concepts & Practicals Page 2


CONCEPT 01
var, let & const — Scoping & Hoisting
var is function-scoped and hoisted to the top of its function (initialized as undefined). let and const are
block-scoped and hoisted but NOT initialized — accessing them before declaration causes a
ReferenceError (Temporal Dead Zone).

// var — function scoped


function example() {
[Link](x); // undefined (hoisted)
var x = 10;
if (true) {
var x = 20; // same variable!
}
[Link](x); // 20
}

// let — block scoped


function example2() {
let y = 10;
if (true) {
let y = 20; // different variable
[Link](y); // 20
}
[Link](y); // 10
}

// const — must be initialized, can't be reassigned


const PI = 3.14159;
// PI = 3; // TypeError
const obj = { a: 1 };
obj.a = 2; // OK — object properties can change

■ Interview Tip

Always prefer const by default. Use let only when reassignment is needed. Avoid var in modern
code.

CONCEPT 02
Data Types & Type Coercion
JavaScript has 7 primitive types: string, number, bigint, boolean, undefined, null, symbol — and 1
complex type: object (includes arrays, functions). Type coercion happens automatically with == (loose)
but not with === (strict).

JavaScript Interview Prep — Top 20 Concepts & Practicals Page 3


// Primitives
typeof 'hello' // 'string'
typeof 42 // 'number'
typeof true // 'boolean'
typeof undefined // 'undefined'
typeof null // 'object' ← famous bug!
typeof Symbol() // 'symbol'
typeof 42n // 'bigint'

// Type coercion with ==


0 == false // true (coercion)
'' == false // true
null == undefined // true

// Strict equality ===


0 === false // false
null === undefined // false

// Falsy values: false, 0, '', null, undefined, NaN


// Truthy: everything else ([], {}, '0', 'false')
Boolean([]) // true — empty array is truthy!

CONCEPT 03
Functions: Declarations, Expressions & Arrow Functions
Function declarations are hoisted completely. Function expressions and arrow functions are not. Arrow
functions do not have their own this, arguments, or prototype.

// Declaration — hoisted
greet('Alice'); // works before declaration
function greet(name) { return `Hello, ${name}`; }

// Expression — NOT hoisted


// sayHi('Bob'); // TypeError
const sayHi = function(name) { return `Hi, ${name}`; };

// Arrow function — concise, no own 'this'


const add = (a, b) => a + b;

// Arrow vs regular 'this'


const timer = {
seconds: 0,
start() {
setInterval(() => {
[Link]++; // 'this' = timer ✓
}, 1000);
}
};

CONCEPT 04

JavaScript Interview Prep — Top 20 Concepts & Practicals Page 4


Scope & Closures
A closure is formed when an inner function retains access to the outer function's variables even after the
outer function has returned. This is one of the most-asked JavaScript interview topics.

function makeCounter(start = 0) {
let count = start; // private variable
return {
increment() { return ++count; },
decrement() { return --count; },
getCount() { return count; }
};
}

const counter = makeCounter(10);


[Link](); // 11
[Link](); // 12
[Link](); // 11
[Link]([Link]()); // 11

// Classic closure interview trap


for (var i = 0; i < 3; i++) {
setTimeout(() => [Link](i), 100); // 3,3,3 ← trap!
}
// Fix with let (block scope per iteration)
for (let i = 0; i < 3; i++) {
setTimeout(() => [Link](i), 100); // 0,1,2 ✓
}

■ Practical Use Cases

Module pattern, data privacy, memoization, event handlers, partial application.

CONCEPT 05
The 'this' Keyword
this refers to the object that is currently executing the function. Its value depends on how the function is
called, not where it is defined (except arrow functions, which inherit this lexically).

JavaScript Interview Prep — Top 20 Concepts & Practicals Page 5


// 1. Global context
[Link](this); // window (browser) / global (Node)

// 2. Method call — 'this' = owning object


const user = {
name: 'Alice',
greet() { [Link]([Link]); } // 'Alice'
};
[Link]();

// 3. Function call — 'this' = undefined (strict) / window


function show() { [Link](this); }
show(); // undefined in strict mode

// 4. Arrow function — inherits enclosing 'this'


const obj = {
value: 42,
getValue: () => [Link] // undefined — wrong!
};

// 5. Explicit binding
function introduce(greeting) {
[Link](`${greeting}, I'm ${[Link]}`);
}
[Link]({ name: 'Bob' }, 'Hello'); // Hello, I'm Bob

JavaScript Interview Prep — Top 20 Concepts & Practicals Page 6


CONCEPT 06
Prototypes & Prototype Chain
Every JavaScript object has a hidden [[Prototype]] property (accessible via __proto__ or
[Link]()). When a property is accessed, JS walks the prototype chain until it finds it or
reaches null.

function Animal(name) {
[Link] = name;
}
[Link] = function() {
return `${[Link]} makes a sound.`;
};

const dog = new Animal('Rex');


[Link](); // 'Rex makes a sound.'

// Prototype chain lookup:


// dog → [Link] → [Link] → null
// Check prototype
[Link](dog) === [Link]; // true
dog instanceof Animal; // true

// hasOwnProperty — own vs inherited


[Link]('name'); // true (own)
[Link]('speak'); // false (inherited)

CONCEPT 07
Object Methods: call, apply & bind
These three methods explicitly set this for a function. call passes args individually, apply takes an array of
args, bind returns a new permanently-bound function.

JavaScript Interview Prep — Top 20 Concepts & Practicals Page 7


function greet(greeting, punctuation) {
return `${greeting}, ${[Link]}${punctuation}`;
}
const person = { name: 'Alice' };

// call — args one by one


[Link](person, 'Hello', '!'); // 'Hello, Alice!'

// apply — args as array


[Link](person, ['Hi', '?']); // 'Hi, Alice?'

// bind — returns new function


const boundGreet = [Link](person, 'Hey');
boundGreet('.'); // 'Hey, Alice.'
boundGreet('!!'); // 'Hey, Alice!!'

// Practical: borrowing array methods


const args = { 0: 'a', 1: 'b', length: 2 };
[Link](args); // ['a', 'b']

CONCEPT 08
Destructuring & Spread / Rest Operators

// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
// first=1, second=2, rest=[3,4,5]
// Object destructuring with renaming & defaults
const { name: userName = 'Guest', age = 18 } = { name: 'Alice' };
// userName='Alice', age=18
// Spread — expand iterable
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1,2,3,4,5]
const clone = { ...obj, newProp: true }; // shallow copy

// Rest — collect remaining args


function sum(first, ...numbers) {
return first + [Link]((a, b) => a + b, 0);
}
sum(1, 2, 3, 4); // 10

// Swap without temp variable


let a = 1, b = 2;
[a, b] = [b, a]; // a=2, b=1

CONCEPT 09
Classes & Inheritance (ES6+)
ES6 classes are syntactic sugar over prototypal inheritance. They support constructor, extends, super,
static methods, and private fields (#).

JavaScript Interview Prep — Top 20 Concepts & Practicals Page 8


class Animal {
#sound; // private field
constructor(name, sound) {
[Link] = name;
this.#sound = sound;
}
speak() { return `${[Link]} says ${this.#sound}`; }
static create(name, sound) { return new Animal(name, sound); }
}

class Dog extends Animal {


constructor(name) {
super(name, 'woof'); // call parent constructor
}
fetch(item) { return `${[Link]} fetches ${item}`; }
}

const rex = new Dog('Rex');


[Link](); // 'Rex says woof'
[Link]('ball'); // 'Rex fetches ball'
rex instanceof Dog; // true
rex instanceof Animal; // true

JavaScript Interview Prep — Top 20 Concepts & Practicals Page 9


CONCEPT 10
Callbacks & Callback Hell
A callback is a function passed as an argument to another function, executed after a task completes.
Nesting callbacks leads to 'callback hell' — hard to read and maintain code.

// Callback example
function fetchUser(id, callback) {
setTimeout(() => callback(null, { id, name: 'Alice' }), 500);
}

// Callback hell — hard to read ■


fetchUser(1, (err, user) => {
fetchPosts([Link], (err, posts) => {
fetchComments(posts[0].id, (err, comments) => {
// deeply nested...
});
});
});

// Solution: Promises or async/await (see next concepts)

CONCEPT 11
Promises
A Promise represents a future value — pending, fulfilled, or rejected. Promises solve callback hell with
chainable .then() and .catch().

// Creating a Promise
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

// Chaining
fetch('/api/user')
.then(res => [Link]())
.then(user => [Link]([Link]))
.catch(err => [Link]('Error:', err))
.finally(()=> [Link]('Done'));

// Promise combinators
[Link]([p1, p2, p3]) // all resolve or any rejects
[Link]([p1, p2]) // waits for all to settle
[Link]([p1, p2]) // first to settle wins
[Link]([p1, p2]) // first to fulfill wins

CONCEPT 12
async / await

JavaScript Interview Prep — Top 20 Concepts & Practicals Page 10


async/await is syntactic sugar over Promises, making async code look synchronous. An async function
always returns a Promise. await pauses execution until the Promise resolves.

async function getUser(id) {


try {
const res = await fetch(`/api/users/${id}`);
if (![Link]) throw new Error(`HTTP ${[Link]}`);
const user = await [Link]();
return user;
} catch (error) {
[Link]('Failed to fetch user:', error);
throw error; // re-throw if needed
}
}

// Parallel execution with await


async function loadDashboard() {
const [user, posts] = await [Link]([
getUser(1),
getPosts(1)
]);
// Both fetched in parallel ✓
return { user, posts };
}

■■ Common Mistake

Avoid using await inside a forEach loop — use for...of or [Link] instead.

CONCEPT 13
The Event Loop & Call Stack
JavaScript is single-threaded. The Event Loop continuously checks if the call stack is empty and moves
tasks from the task queue (macrotasks) or microtask queue (Promises) onto the stack. Microtasks
always run before macrotasks.

[Link]('1 - synchronous');

setTimeout(() => [Link]('2 - macrotask'), 0);

[Link]()
.then(() => [Link]('3 - microtask'));

[Link]('4 - synchronous');

// Output order: 1 → 4 → 3 → 2
// Sync first, then microtasks, then macrotasks
// Microtasks: [Link], queueMicrotask, MutationObserver
// Macrotasks: setTimeout, setInterval, I/O, UI events

JavaScript Interview Prep — Top 20 Concepts & Practicals Page 11


CONCEPT 14
Array Methods: map, filter, reduce
These three are essential functional programming tools. They don't mutate the original array and each
returns something new.

const products = [
{ name: 'Apple', price: 1.5, inStock: true },
{ name: 'Banana', price: 0.5, inStock: false },
{ name: 'Cherry', price: 3.0, inStock: true },
];

// map — transform each element


const names = [Link](p => [Link]);
// ['Apple', 'Banana', 'Cherry']
// filter — keep matching elements
const available = [Link](p => [Link]);
// [Apple, Cherry]
// reduce — fold to a single value
const total = [Link]((sum, p) => sum + [Link], 0);
// 5.0
// Chained — only in-stock product names
const result = products
.filter(p => [Link])
.map(p => [Link]());
// ['APPLE', 'CHERRY']

CONCEPT 15
for...of vs for...in

// for...of — iterates VALUES (arrays, strings, Maps, Sets)


const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
[Link](fruit); // 'apple', 'banana', 'cherry'
}

// for...in — iterates KEYS/INDICES (objects, arrays)


const person = { name: 'Alice', age: 30 };
for (const key in person) {
[Link](`${key}: ${person[key]}`);
}
// name: Alice
// age: 30
// Caution: for...in on arrays iterates indices as strings
// and can include prototype properties — use for...of instead
// Other iteration: forEach, entries(), keys(), values()
[Link]((v, i) => [Link](i, v));

JavaScript Interview Prep — Top 20 Concepts & Practicals Page 12


CONCEPT 16
Event Delegation & Bubbling
Events bubble up from the target element to its ancestors. Event delegation attaches one listener to a
parent instead of many on children — efficient and works for dynamic elements.

// Instead of adding listener to every button:


[Link]('list').addEventListener('click', (e) => {
// Delegate to target
if ([Link]('[Link]')) {
const item = [Link]('li');
[Link]();
}
if ([Link]('[Link]')) {
// handle edit...
}
});

// Stop propagation if needed


[Link]('click', (e) => {
[Link](); // stops bubbling
[Link](); // stops default action
});

JavaScript Interview Prep — Top 20 Concepts & Practicals Page 13


CONCEPT 17
Debouncing & Throttling
Debounce: execute only after a pause in calls (e.g., search input). Throttle: execute at most once per
time interval (e.g., scroll, resize).

// Debounce — fires after user stops typing


function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
const onSearch = debounce(query => fetchResults(query), 300);
[Link]('input', e => onSearch([Link]));

// Throttle — fires at most once per interval


function throttle(fn, limit) {
let inThrottle = false;
return (...args) => {
if (!inThrottle) {
fn(...args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
const onScroll = throttle(() => updateNav(), 100);
[Link]('scroll', onScroll);

CONCEPT 18
Modules (ES Modules & CommonJS)

JavaScript Interview Prep — Top 20 Concepts & Practicals Page 14


// ■■ ES Modules (browser, modern Node) ■■
// [Link] — named exports
export const add = (a, b) => a + b;
export const PI = 3.14159;
export default function multiply(a, b) { return a * b; }

// [Link] — imports
import multiply, { add, PI } from './[Link]';
import * as math from './[Link]'; // namespace import

// Dynamic import (code splitting)


const { add } = await import('./[Link]');

// ■■ CommonJS ([Link]) ■■
// [Link]
[Link] = { add: (a,b) => a+b };

// [Link]
const { add } = require('./math');

CONCEPT 19
Memoization & Pure Functions
A pure function always returns the same output for the same input and has no side effects. Memoization
caches expensive function results to avoid recomputation.

// Pure function — no side effects


const double = x => x * 2; // same input → same output always

// Memoize — generic caching wrapper


function memoize(fn) {
const cache = new Map();
return function(...args) {
const key = [Link](args);
if ([Link](key)) return [Link](key);
const result = [Link](this, args);
[Link](key, result);
return result;
};
}

// Expensive Fibonacci without memoization = O(2^n)


const fib = memoize(function(n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
});

fib(40); // fast ✓ (O(n) with cache)

CONCEPT 20
Error Handling & try/catch/finally

JavaScript Interview Prep — Top 20 Concepts & Practicals Page 15


Robust error handling is crucial in production code. Use try/catch/finally for synchronous and async
errors, and create custom error types for clarity.

// Custom Error class


class ValidationError extends Error {
constructor(message, field) {
super(message);
[Link] = 'ValidationError';
[Link] = field;
}
}

// Sync error handling


function parseJSON(str) {
try {
return [Link](str);
} catch (e) {
if (e instanceof SyntaxError) {
throw new ValidationError('Invalid JSON', 'body');
}
throw e; // re-throw unknown errors
} finally {
[Link]('parse attempt complete'); // always runs
}
}

// Async error handling


async function loadData() {
try {
const data = await fetch('/api/data').then(r => [Link]());
return data;
} catch (err) {
[Link]('Network error:', [Link]);
return null; // graceful fallback
}
}

■ Final Interview Tip

Always handle both synchronous throws and async rejections. Unhandled promise rejections crash
[Link] apps. Use [Link]('unhandledRejection', ...) or
[Link]('unhandledrejection', ...) as a last resort global handler.

JavaScript Interview Prep — Top 20 Concepts & Practicals Page 16

You might also like