Category 1: Beginner Level (The Foundation)
These questions test your basic understanding of JavaScript syntax, core concepts, and simple DOM manipulation.
1. Basic Understanding & IQ
What are the different data types in JavaScript?
Explain the difference between
==
and===
.What is the difference between
null
andundefined
?How does the
typeof
operator work? What is the output oftypeof null
?What is variable hoisting?
What are the differences between
var
,let
, andconst
?What is the
use strict
directive? What are its benefits?How do you create a comment in JavaScript?
2. Coding Examples & Output
What is the output of the following code?
console.log(1 + "2" + "2"); console.log(1 + +"2" + "2"); console.log(1 + -"1" + "2"); console.log(+"1" + "1" + "2");
What will the code below output?
for (var i = 0; i < 3; i++) { setTimeout(function() { console.log(i); }, 1000 + i); }
Predict the output:
console.log(false == '0') console.log(false === '0')
3. Real-Life Scenarios & DOM
How would you select an HTML element by its ID using vanilla JS?
How do you change the text content of a paragraph element with id
"demo"
?How do you create a new
<li>
element and add it to an existing<ul>
?How do you attach a click event listener to a button?
Category 2: Intermediate Level (The Core Competency)
This section delves into the heart of JavaScript: functions, object-oriented programming, and asynchronous operations.
1. Functions & Closures
What is a closure? Provide a practical example of its use (e.g., data privacy, currying).
Explain the concept of
this
keyword in JavaScript. How is its value determined?What is the difference between
.call()
,.apply()
, and.bind()
? Show code examples.What is an IIFE (Immediately Invoked Function Expression) and why is it used?
What is a higher-order function? What is a callback function?
Explain the concept of currying in JavaScript.
2. Object-Oriented JavaScript
What are the different ways to create objects in JavaScript?
Explain prototypal inheritance. How is it different from classical inheritance?
What is the prototype chain?
What are the different ways to implement inheritance in ES5 and ES6?
What are getters and setters?
3. Asynchronous JavaScript (The Interview Favorite)
What is the difference between synchronous and asynchronous code?
Explain the event loop in JavaScript. Use a diagram if needed.
What are callbacks? What is "callback hell"?
What is a Promise? What are its states (
pending
,fulfilled
,rejected
)?How do you handle errors in a promise chain?
What does
Promise.all
do? What aboutPromise.race
?What is
async/await
? How does it make asynchronous code easier to write and read?
4. Coding Examples & Scenarios
Fix the "setTimeout inside loop" problem from the beginner section using ES6.
Write a function that flattens a nested array (e.g.,
[1, [2, [3]], 4]
->[1, 2, 3, 4]
).Implement a debounce function.
Create a simple Promise that resolves after a given time delay. Then consume it with
.then()
and withasync/await
.How would you copy an object to avoid mutating the original one? (Deep vs. Shallow copy).
Write a function to check if a string is a palindrome.
Explain and implement the
memorize
function.
Category 3: Expert Level (The Deep Dive)
These questions separate senior developers from the rest. They involve advanced language mechanics, performance, and complex problem-solving.
1. Advanced Language Mechanics
Explain the Temporal Dead Zone (TDZ) in relation to
let
andconst
.What are JavaScript generators (
function*
) andyield
? Provide a use case.Explain the concept of
Symbol
and its practical applications.What are JavaScript Proxies and Reflect? Give a practical example.
Explain the difference between
Object.freeze()
,Object.seal()
, andObject.preventExtensions()
.What are Web Workers and why are they used?
2. Performance & Memory
What is a memory leak in JavaScript? Name three common ways they occur (e.g., global variables, forgotten timers, detached DOM elements).
How does the garbage collection mechanism work in JavaScript?
What is the difference between
event.preventDefault()
,event.stopPropagation()
, andevent.stopImmediatePropagation()
?How would you optimize a website's scrolling performance?
3. Complex Scenarios & System Design
How would you implement a function to execute a maximum of
n
API calls in parallel at any time?Design a pub/sub (publish-subscribe) pattern in JavaScript.
Implement a function to perform deep comparison between two objects.
How would you create your own implementation of
Promise.all
?Explain and code a Throttle function. How is it different from Debounce?
How does the V8 engine compile and execute JavaScript code? (Hint: JIT, interpreter, compiler)
What are service workers? How do they enable offline functionality?
4. Tricky Output & IQ (The Brain Teasers)
What is the output?
let a = {}; let b = { key: 'b' }; let c = { key: 'c' }; a[b] = 123; a[c] = 456; console.log(a[b]);
Explain the output of this code involving
this
:const obj = { name: 'JavaScript', print: () => { console.log(this.name); } }; obj.print();
What does this code do, and what's the potential issue?
const isArray = (input) => { return Object.prototype.toString.call(input) === '[object Array]'; }; // Why not just use `Array.isArray` or `typeof`?
Bonus: Data-Oriented & Algorithmic Thinking
Array Manipulation: Write a function to find the unique values in an array. Then, do it without using
Set
.Objects & Data Structures: Given a large array of user objects, how would you efficiently find a user by their
id
? How would you group users by theirdepartment
?String Processing: Write a function that returns the most frequently occurring character in a string.
Coding Challenge: Implement a function to reverse a string in-place (without using
.reverse()
or creating a new array).Real-Life Scenario: You have a stream of rapidly incoming data points (e.g., stock prices). You need to update a "current price" display but can't update the UI more than once every 200ms for performance. How do you architect this?
Deep Dive: Key JavaScript Topics with Examples
To truly master these questions, let's break down some of the most critical topics with clear, illustrative examples.
1. Closures in Action
A closure is a function that has access to its own scope, the outer function's scope, and the global scope, even after the outer function has finished executing.
Interview Question: Explain a practical use of a closure.
Example: Data Privacy
function createCounter() { let count = 0; // `count` is private to this function return { increment: function() { count++; return count; }, decrement: function() { count--; return count; }, getValue: function() { return count; } }; } const counter = createCounter(); console.log(counter.increment()); // 1 console.log(counter.increment()); // 2 console.log(counter.decrement()); // 1 console.log(counter.getValue()); // 1 console.log(counter.count); // undefined (It's private!)
Explanation: The count
variable is enclosed within createCounter
. The returned object's methods form closures that remember and can access count
, but nothing else from the outside can, providing perfect data encapsulation.
2. The this
Keyword Demystified
The value of this
is determined by how a function is called.
Interview Question: How is the value of this
determined?
Example: Different Binding Rules
const person = { name: 'Alice', greet: function() { console.log('Hello, ' + this.name); } }; // 1. Implicit Binding: `this` is the object before the dot. person.greet(); // "Hello, Alice" // 2. Explicit Binding: Using call, apply, or bind to set `this`. const greetFunction = person.greet; const otherPerson = { name: 'Bob' }; greetFunction.call(otherPerson); // "Hello, Bob" // 3. New Binding: `this` refers to the newly created instance. function Person(name) { this.name = name; } const charlie = new Person('Charlie'); console.log(charlie.name); // "Charlie" // 4. Default Binding: In non-strict mode, `this` is the global object (window in browsers). // In strict mode, it's undefined. function standalone() { console.log(this); } standalone(); // Window (or undefined in strict mode) // 5. Arrow Functions: `this` is lexically bound (it uses `this` from its surrounding scope). const arrowPerson = { name: 'Dave', greet: () => { console.log('Hello, ' + this.name); // `this` is not arrowPerson! } }; arrowPerson.greet(); // "Hello, " (likely window.name or undefined)
3. Asynchronous JavaScript: Callback vs Promise vs Async/Await
Interview Question: Refactor a callback-based function to use Promises and then Async/Await.
Example: Simulating API Calls
// 1. Callback Hell (Pyramid of Doom) function fetchDataCallback(callback) { setTimeout(() => { console.log("Data fetched!"); callback("Success Data"); }, 1000); } fetchDataCallback((data) => { processDataCallback(data, (processedData) => { saveDataCallback(processedData, (result) => { console.log(result); }); }); }); // 2. Promises (Chaining for readability) function fetchDataPromise() { return new Promise((resolve) => { setTimeout(() => { console.log("Data fetched!"); resolve("Success Data"); }, 1000); }); } fetchDataPromise() .then(processDataPromise) // Assume these return promises too .then(saveDataPromise) .then(result => console.log(result)) .catch(error => console.error("Something went wrong:", error)); // 3. Async/Await (Synchronous-looking style) async function main() { try { const data = await fetchDataPromise(); const processedData = await processDataPromise(data); const result = await saveDataPromise(processedData); console.log(result); } catch (error) { console.error("Something went wrong:", error); } } main();
Explanation: Async/Await is syntactic sugar on top of Promises. It makes the code much easier to read and reason about by removing the nested .then()
chains and allowing for standard try/catch
error handling.
Category 4: Modern JavaScript (ES6+)
These questions test your knowledge of modern syntax and features that are essential in contemporary development.
1. Variables & Scoping
Besides block scoping, what are other key differences between
let
/const
andvar
?What is the Temporal Dead Zone (TDZ)? Provide a code example that causes a TDZ error.
2. Functions
What are Arrow Functions? List their key behavioral differences from regular
function
declarations (e.g.,this
,arguments
, use withnew
).What are default function parameters? How do they work?
3. Objects & Arrays
What is destructuring assignment? Show examples for objects and arrays.
What is the spread syntax (
...
)? What is the rest parameter? How are they different?What are computed property names in object literals?
4. Strings & Templates
What are template literals? What can you do with them that you couldn't with regular strings? (String interpolation, multi-line strings, tagged templates).
5. Advanced Data Structures
What are
Map
andSet
? How are they different from regular Objects and Arrays? When would you use them?What are
WeakMap
andWeakSet
? What are their main use cases related to garbage collection?
Coding Example: Modern Syntax
Refactor this old-style code using modern ES6+ features:
var user = { firstName: 'John', lastName: 'Doe', age: 30 }; var firstName = user.firstName; var lastName = user.lastName; var fullName = firstName + ' ' + lastName; function createEmail(firstName, age) { return firstName.toLowerCase() + age + '@example.com'; } var email = createEmail(user.firstName, user.age);
Category 5: Browser & DOM API Expertise
1. DOM Manipulation & Traversal
What is the difference between
children
andchildNodes
?What is the difference between
textContent
andinnerHTML
? Which is safer and why?How do you check if an element matches a specific CSS selector?
How do you get the dimensions and position of an element? (e.g.,
getBoundingClientRect()
).
2. Event System
What is event delegation and why is it useful? Provide a code example.
Explain the three phases of event propagation in the DOM (Capturing, Target, Bubbling).
How would you create and dispatch a synthetic event?
3. Storage & APIs
Compare
localStorage
,sessionStorage
, andcookies
. (Persistence, size limits, server accessibility).What are the key differences between the
XMLHttpRequest
object and thefetch
API?How do you cancel a
fetch
request? (Hint:AbortController
).
4. Performance & Rendering
What is the Critical Rendering Path? How would you optimize it?
What are
requestAnimationFrame
andrequestIdleCallback
used for?What is debouncing and throttling? Write a code implementation for a search input field.
Category 6: Testing & Tooling
What is unit testing? Name a popular JavaScript testing framework (e.g., Jest, Mocha).
What is the difference between
module.exports
/require
(CommonJS) andexport
/import
(ES6 Modules)?What is a linter (e.g., ESLint) and a formatter (e.g., Prettier)? Why are they important?
What is tree shaking? How does it help with bundle size?
Final Brain Teasers (Expert++)
The Classic: Implement
Function.prototype.bind
on your own.The Concurrency Problem: Write a function
limitConcurrency(tasks, limit)
that takes an array of async tasks (functions that return promises) and a concurrency limit. It should execute no more thanlimit
tasks at once, executing a new one as soon as one finishes.The Polyfill: Write a polyfill for
Array.prototype.reduce
.The Recursion Challenge: Implement a function to deeply freeze an object (make it and all its nested properties immutable).
The Logic Puzzle: Create a function that checks if a given value is an array without using
Array.isArray
, theinstanceof
operator, or checking itsconstructor
name.
No comments:
Post a Comment
Thanks for your valuable comment...........
Md. Mominul Islam