JavaScript Interview Questions and Answers
TL;DR
Here is a clear, practical guide to JavaScript: the fundamentals, the best practices that actually move the needle, common mistakes to avoid, concrete data points, and a short FAQ. Everything is structured so you can apply it to real projects today.
Key takeaways
- A closure is a function bundled with references to its surrounding lexical scope, letting it remember variables after the outer function returns.
- Break long tasks into smaller chunks and yield to the main thread to keep interfaces responsive.
- Promise callbacks are microtasks and always run before the next macrotask such as a setTimeout callback.
- Most JavaScript performance wins come from reducing main-thread work, not micro-optimizing tight loops.
- The event loop is single-threaded: it runs one task to completion, drains all microtasks, then optionally renders.
This is a practical, up-to-date guide to JavaScript — what it is, why it matters in 2026, and how to apply it in real projects. It is written for developers and founders who want clear answers and proven best practices, not filler.
Whether you're just starting out or leveling up, treat this as a working reference you can return to. Every section is built to be skimmed, applied, and shared.
What Is Hoisting and the Temporal Dead Zone?
During compilation, JavaScript registers declarations before any code runs. var declarations are initialized to undefined and function declarations are fully hoisted, so they can be called before their textual position. let, const, and class are hoisted too, but left uninitialized.
That uninitialized window is the temporal dead zone (TDZ): referencing the binding before its declaration throws a ReferenceError rather than returning undefined. This is a feature, catching use-before-declaration bugs early.
- Prefer
constby default andletwhen reassignment is needed. - Avoid
varin modern code to sidestep function-scope surprises. - Function declarations are safe to call early; function expressions are not.
Understanding hoisting demystifies many "undefined" and "cannot access before initialization" errors.
What Are the Core Advanced JavaScript Concepts to Master?
Beyond syntax, a handful of concepts unlock the language. The prototype chain explains inheritance: objects delegate property lookups to their prototype, and class is sugar over this mechanism. Lexical scope and closures explain how state is captured. The event loop explains concurrency without threads.
A practical study list:
- Closures, scope, and the module pattern.
- The prototype chain and
classsemantics. - The event loop, microtasks, and
async/await. - Immutability, pure functions, and avoiding shared mutable state.
- ES modules, tree shaking, and dynamic
import().
These ideas reinforce one another. Understanding the event loop, for instance, makes promises, performance tuning, and debugging async ordering far more intuitive than memorizing rules in isolation.
How Does the this Keyword Bind?
this is determined by how a function is called, not where it is defined. There are four main rules, checked roughly in this order: new binding, explicit binding via call/apply/bind, implicit binding from the object before the dot, and default binding to undefined in strict mode (or the global object otherwise).
Arrow functions are the exception: they have no own this and instead capture it lexically from the enclosing scope, which makes them ideal for callbacks inside methods.
obj.method()bindsthistoobj.- A detached
const fn = obj.methodloses that binding. fn.bind(obj)returns a permanently bound copy.
Losing this when passing a method as a callback is one of the most common JavaScript bugs; arrow functions or bind solve it.
What Is the Difference Between Microtasks and Macrotasks?
Macrotasks include setTimeout, setInterval, message events, and I/O callbacks. Microtasks include promise .then/.catch/.finally reactions, queueMicrotask, and await continuations. The defining rule: after each macrotask, the engine drains the microtask queue completely before the next macrotask or paint.
- Microtasks have higher priority and can starve rendering if you enqueue them in an unbounded loop.
- One
setTimeout(fn, 0)waits for the next macrotask turn, so it always runs after pending promises. awaitsplits a function: code after it resumes as a microtask.
Knowing this prevents subtle bugs where state appears to update in the wrong order, and explains why heavy promise chains can delay visual updates.
Why Does My Async Code Run in an Unexpected Order?
Most ordering confusion comes from forgetting that await yields control. Everything before the first await runs synchronously; everything after resumes later as a microtask. Meanwhile, synchronous code that called the async function keeps executing first.
Consider:
console.log('A');
(async () => {
console.log('B');
await null;
console.log('D');
})();
console.log('C');
The output is A B C D. B runs synchronously, the function suspends at await, C runs, then the microtask resumes with D. Mapping out which lines run before and after each await resolves nearly all of these surprises without a debugger.
How Do You Optimize JavaScript Performance?
The biggest wins come from doing less on the main thread, not from clever micro-optimizations. Profile first with the browser Performance panel or Lighthouse, find the long tasks, then attack them. Optimize for the metric users feel: Interaction to Next Paint should stay under 200 ms.
High-impact techniques:
- Break long tasks into chunks and yield with
scheduler.yield()orsetTimeout. - Move CPU-heavy work to a Web Worker so the UI thread stays free.
- Debounce or throttle high-frequency events like
scroll,resize, andinput. - Defer non-critical scripts and code-split large bundles.
- Batch DOM reads and writes to avoid layout thrashing.
Measure again after each change; assumptions about hotspots are often wrong.
JavaScript: Key Facts and Data
According to recent industry research and the official documentation linked below:
- async/await was standardized in ES2017 (ES8) and is supported by all modern browsers and Node.js 8+
- JavaScript is used by roughly 98% of all websites as a client-side language, per W3Techs surveys
- ECMAScript is updated annually, with ES2025 being the edition ratified in June 2025 by Ecma International
Quick-Reference Summary
A map of what this guide covers:
| Topic | What you'll learn |
|---|---|
| What Is Hoisting and the Temporal Dead Zone? | During compilation, JavaScript registers declarations before any code runs. |
| What Are the Core Advanced JavaScript Concepts to Master? | Beyond syntax, a handful of concepts unlock the language. |
| How Does the this Keyword Bind? | this is determined by how a function is called, not where it is defined. |
| What Is the Difference Between Microtasks and Macrotasks? | Macrotasks include setTimeout, setInterval, message events, and I/O callbacks. |
| Why Does My Async Code Run in an Unexpected Order? | Most ordering confusion comes from forgetting that await yields control. |
| How Do You Optimize JavaScript Performance? | The biggest wins come from doing less on the main thread, not from clever micro-optimizations. |
How to Get Started with JavaScript
A simple path that works:
- Learn the fundamentals of JavaScript from primary sources, not just tutorials.
- Build one small, real project end to end.
- Get feedback, refactor, and add tests.
- Ship it publicly and document what you learned.
- Repeat with a slightly harder project each time.
Build It with a World-Class Full Stack Developer
Sandeep Kumar Chaudhary is a full stack world-class developer. If you want to turn this into a real, production-ready product, get in touch — message directly on WhatsApp at +9779802348957 for a fast, no-pressure consult.
You can also explore the projects already shipped to thousands of users, or start a conversation here.
Final Thoughts
A closure is a function bundled with references to its surrounding lexical scope, letting it remember variables after the outer function returns. The developers and teams who win in 2026 pair strong fundamentals with consistent shipping. Start small, stay curious, build in public, and revisit this guide as your skills grow.
Sources and Further Reading
Frequently Asked Questions
What is javascript?
Beyond syntax, a handful of concepts unlock the language. The prototype chain explains inheritance: objects delegate property lookups to their prototype, and class is sugar over this mechanism. This guide covers JavaScript end to end — core concepts, best practices, concrete data, and a step-by-step approach you can apply right away.
Why does a Promise callback run before setTimeout?
Promise callbacks are microtasks, and `setTimeout` callbacks are macrotasks. After each task finishes, the event loop drains the entire microtask queue before running the next macrotask or rendering. So a resolved promise's `.then` always executes before a `setTimeout(fn, 0)`, even when both are scheduled at the same moment.
What is a closure in JavaScript in simple terms?
A closure is a function that remembers the variables from the scope where it was created, even after that outer scope has finished running. This lets the function keep private state between calls. Closures power patterns like counters, function factories, and data hiding, and they share the actual variable binding rather than a copy.
What is the fastest way to improve JavaScript performance?
Profile first, then reduce main-thread work. Break long tasks into smaller chunks, yield to the event loop, move CPU-heavy code to a Web Worker, and debounce or throttle frequent events. Defer and code-split large scripts. Optimize for Interaction to Next Paint under 200 ms rather than guessing at micro-optimizations.
Should I use ES modules or CommonJS?
Prefer ES modules for new code. They are the language standard, use static `import`/`export` that enables tree shaking and smaller bundles, support top-level `await`, and run natively in browsers and modern Node.js. CommonJS with `require` is still common in older Node projects, but ESM is the forward-looking default.
Sandeep Kumar Chaudhary
Full Stack Software Developer· Nepal's SEO, AEO, GEO & AIO expert and share-market educator. More about me
