Prepare for your next JavaScript interview with these 20 essential questions covering basics to advanced concepts. Includes code snippets, hoisting, closures, promises, and more!
1. How Can We Insert JavaScript Code?
JavaScript is embedded in HTML using the <script>
tag. Typically, it can be placed in either the <head>
or <body>
. However, the best practice is to load it just before the closing </body>
tag because this ensures better page performanc
Example:
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
Best Practice: Specifically, place scripts at the bottom of <body>
so that DOM elements are fully loaded before script execution. As a result, this prevents potential errors where JavaScript tries to access elements that haven’t been rendered yet.
2. How Does JavaScript Display Data?
JavaScript can output data in multiple ways:
Method | Description | Example |
---|---|---|
innerHTML | Modifies HTML content | element.innerHTML = "New Content" |
document.write() | Writes directly to HTML (avoid in production) | document.write("Hello") |
window.alert() | Shows an alert box | alert("Warning!") |
console.log() | Logs to browser console | console.log("Debugging") |
3. What Are JavaScript Data Types?
JavaScript has primitive and non-primitive (reference) data types:
Primitive Types:
String
("Hello"
)Number
(42
,3.14
)Boolean
(true
,false
)Undefined
(let a;
)Null
(let b = null;
)Symbol
(const sym = Symbol('id')
)BigInt
(9007199254740991n
)
Non-Primitive Types:
Object
({}
)Array
([]
)Function
(function() {}
)
4. What Are the Different Variables in JavaScript?
JavaScript has var
, let
, and const
for variable declaration.
Feature | var | let | const |
---|---|---|---|
Scope | Function-scoped | Block-scoped | Block-scoped |
Re-declaration | Allowed | Not allowed | Not allowed |
Reassignment | Allowed | Allowed | Not allowed |
Example:
var x = 10;
x = 20; // Allowed
let y = 30;
y = 40; // Allowed
const z = 50;
z = 60; // Error (Cannot reassign const)
5. What Is JavaScript Hoisting?
Hoisting moves variable and function declarations to the top of their scope before execution.
Hoisting with var
:
console.log(a); // undefined (declaration hoisted)
var a = 10;
console.log(a); // 10
Hoisting with let
& const
:
console.log(b); // ReferenceError (Temporal Dead Zone)
let b = 20;
6. Difference Between ==
and ===
?
==
checks value only (loose equality).===
checks value + type (strict equality).
Example:
console.log(5 == "5"); // true (type coercion)
console.log(5 === "5"); // false (different types)
7. What Are JavaScript Number Methods?
Method | Description | Example |
---|---|---|
toString() | Converts number to string | (10).toString() → "10" |
toFixed(2) | Rounds to 2 decimal places | 3.1415.toFixed(2) → "3.14" |
toExponential() | Exponential notation | 1000.toExponential() → "1e+3" |
parseInt() | Converts string to integer | parseInt("10.5") → 10 |
8. Is JavaScript Statically or Dynamically Typed?
JavaScript is dynamically typed—variables can change types at runtime.
Example:
let value = 42; // Number
value = "Hello"; // Now a String
value = true; // Now a Boolean
9. What Is NaN
in JavaScript?
NaN
(Not-a-Number) represents an invalid number.
Key Points:
typeof NaN
→"number"
NaN === NaN
→false
(UseisNaN()
instead)
Example:
console.log(0 / 0); // NaN
console.log(Math.sqrt(-1)); // NaN
console.log(isNaN(NaN)); // true
10. Important String Methods in JavaScript
Method | Description | Example |
---|---|---|
slice(1, 4) | Extracts substring | "Hello".slice(1,4) → "ell" |
split(",") | Splits into array | "a,b,c".split(",") → ["a","b","c"] |
toUpperCase() | Converts to uppercase | "hello".toUpperCase() → "HELLO" |
includes("JS") | Checks substring | "JavaScript".includes("JS") → true |
Advanced JavaScript Questions
11. What Are Closures and How Do They Work?
A closure is a function that remembers its lexical scope even when executed outside it.
Practical Use Cases:
- Data Privacy (Module Pattern)
- Currying & Partial Applications
- Memoization (Caching)
Example:
function outer() {
let count = 0;
return function inner() {
return ++count;
};
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
Explanation:
inner()
retains access tocount
even afterouter()
finishes execution
12. Explain this
Keyword
this
refers to the object it belongs to.
Example:
const person = {
name: "John",
greet: function() {
console.log(`Hello, ${this.name}!`);
}
};
person.greet(); // "Hello, John!"
13. What Are Promises?
Promises handle asynchronous operations.
Example:
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => resolve("Data fetched!"), 1000);
});
fetchData.then(data => console.log(data)); // "Data fetched!"
14. How Does async/await
Work Under the Hood?
async/await
is syntactic sugar over Promises.
Behind the Scenes:
await
pauses execution until the Promise resolves.
An async
function always returns a Promise.
Example:
async function fetchData() {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
return data;
}
// Equivalent to:
function fetchData() {
return fetch("https://api.example.com/data")
.then(response => response.json());
}
🔹 Key Insight:
await
can only be used insideasync
functions.- Error handling requires
try/catch
.
15. What Is Event Bubbling?
Events propagate from child to parent.
Example:
document.querySelector("#child").addEventListener("click", () => {
console.log("Child clicked!");
});
document.querySelector("#parent").addEventListener("click", () => {
console.log("Parent clicked!"); // Also triggers if child is clicked
});
16. What Is the Temporal Dead Zone (TDZ)?
The TDZ is the period where let
and const
variables exist but are uninitialized.
Example:
console.log(x); // ❌ ReferenceError (TDZ) let x = 10;
Why?
var
is hoisted and initialized withundefined
.let/const
are hoisted but not initialized until declaration.
17. What Is Memoization?
Memoization caches function results to avoid redundant computations.
Example:
function memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (cache[key]) return cache[key];
return (cache[key] = fn(...args));
};
}
const factorial = memoize(n => (n <= 1) ? 1 : n * factorial(n - 1));
console.log(factorial(5)); // 120 (cached)
18. What Is the Difference Between call
, apply
, and bind
?
All three methods allow explicit this
binding, but differ in usage:
Method | Syntax | Invocation |
---|---|---|
call | fn.call(this, arg1, arg2) | Immediately invoked |
apply | fn.apply(this, [args]) | Immediately invoked (takes array) |
bind | const boundFn = fn.bind(this) | Returns a new function |
Example:
const user = { name: "Alice" };
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
console.log(greet.call(user, "Hi", "!")); // "Hi, Alice!"
console.log(greet.apply(user, ["Hello", "."])); // "Hello, Alice."
const boundGreet = greet.bind(user, "Hey");
console.log(boundGreet("?")); // "Hey, Alice?"
19. Explain Prototypal Inheritance in JavaScript
JavaScript uses prototypes instead of classical inheritance.
Key Concepts:
- Every object has a
__proto__
property pointing to its prototype. - Functions have a
prototype
property used when called withnew
.
Example:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return `Hello, ${this.name}!`;
};
const john = new Person("John");
console.log(john.greet()); // "Hello, John!"
20. What Is the Event Loop in JavaScript?
The Event Loop is what allows JavaScript to handle asynchronous operations despite being single-threaded.
How It Works:
- Call Stack – Executes synchronous code.
- Web APIs – Handle async tasks (
setTimeout
,fetch
). - Callback Queue – Stores callbacks from Web APIs.
- Event Loop – Moves callbacks from the queue to the stack when the stack is empty.
Example:
console.log("Start");
setTimeout(() => console.log("Timeout"), 0);
Promise.resolve().then(() => console.log("Promise"));
console.log("End");
// Output:
// Start
// End
// Promise
// Timeout
Why?
setTimeout
goes to the Callback Queue.Promise
goes to the Microtask Queue (higher priority).- The Event Loop processes microtasks before callbacks.
Conclusion
These 20 JavaScript interview questions cover fundamental to advanced topics, helping you prepare for technical interviews.
🔗 Further Reading:
🚀 Practice these concepts to ace your next interview!
Suggested Resources:
- Top CSS Interview Questions
- How to prepare for Remote Tech Interview?
- PHP Documentation – Classes and Objects