JavaScript Interview Questions” are essential for anyone preparing for a career in web development or looking to strengthen their foundational knowledge. In this post, we cover the top 15 commonly asked JavaScript questions with simple explanations and examples. From understanding callbacks and promises to exploring closures, the this
keyword, and data types, this guide is perfect for beginners and aspiring developers. Whether you’re preparing for an interview or brushing up on basics, this comprehensive list will help you master JavaScript concepts with ease.
1. Difference between JavaScript and Other Programming Languages
- JavaScript is mostly used for web development to make web pages interactive.
- Unlike many other programming languages, JavaScript runs in the browser (e.g., Chrome, Firefox) but can also run on servers using Node.js.
- JavaScript is loosely typed, meaning you don’t need to specify variable types like
int
,string
, etc. - It is an interpreted language, so the code runs directly without needing to be compiled, unlike Java or C++.
2. Explain Execution Context and Event Loop in JavaScript
- Execution Context:
It’s like an environment where the code is executed. There are two types:- Global Execution Context: The base environment where the code starts running.
- Function Execution Context: Created when a function is called.
Each execution context has two main parts:
- Memory: Stores variables and functions.
- Code: Executes the code line by line.
- Event Loop:
JavaScript uses the event loop to handle asynchronous tasks like timers (setTimeout
), API calls, etc.
Steps:- Code runs in the call stack.
- Asynchronous tasks go to the web APIs and then to the callback queue.
- The event loop keeps checking if the call stack is empty, then moves callbacks from the queue to the stack.
3. Difference Between let
, const
, and var
var
:- Old way of declaring variables.
- Scope: Function-scoped (works inside a function only).
- Can be redeclared and updated.
let
:- Newer way of declaring variables.
- Scope: Block-scoped (works inside
{}
). - Can be updated but not redeclared.
const
:- Used for constants (values that don’t change).
- Scope: Block-scoped.
- Cannot be updated or redeclared.
4. Primitive and Non-Primitive Data Types
- Primitive Data Types: Simple and cannot be changed directly. Examples:
string
(e.g., “Hello”)number
(e.g., 42)boolean
(e.g., true/false)undefined
null
symbol
bigint
- Non-Primitive Data Types: Complex and can be modified.
Example:- Objects (e.g.,
{name: "John"}
) - Arrays (e.g.,
[1, 2, 3]
)
- Objects (e.g.,
5. What is the Nullish Coalescing Operator?
- The Nullish Coalescing Operator (
??
) checks if a value is null or undefined.
If it is, it returns the second value. Otherwise, it returns the first value.
let value = null;
let result = value ?? “Default Value”;
console.log(result); // Output: “Default Value”
6. What is the Arrow Function and How is it Different from Normal Functions?
Arrow Functions are a shorter way to write functions.
Example:
let sum = (a, b) => a + b;
- Differences:
- Doesn’t have its own
this
: It uses thethis
of its surrounding scope. - Can’t be used as constructors (you can’t use
new
with them).
- Doesn’t have its own
7. What is IIFE?
- IIFE stands for Immediately Invoked Function Expression.
- It’s a function that runs as soon as it is defined.
Example:
(function () { console.log(“I am an IIFE!”); })();
8. What is Closure in JavaScript?
- A closure is when a function remembers variables from its outer function, even after the outer function has finished running.
Example:
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
let counter = outer();
counter(); // 1
counter(); // 2
Here, the inner
function remembers count
from outer
.
9. What is the this
Keyword?
this
refers to the object that is calling the function.- In the global scope,
this
refers to thewindow
object (in browsers).
Example:
const obj = {
name: “John”,
greet: function () {
console.log(this.name);
},
};
obj.greet(); // Output: “John”
10. What is Prototype and Prototype Inheritance?
- Prototype: Every object in JavaScript has a hidden property called
__proto__
that links to another object. - Prototype Inheritance: Objects can inherit properties and methods from their prototype.
Example:
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function () {
console.log(“Hello, ” + this.name);
};
let john = new Person(“John”);
john.sayHello(); // “Hello, John”
11. Difference Between map
, filter
, and find
map
: Creates a new array by applying a function to each element.filter
: Returns a new array with elements that match a condition.find
: Returns the first element that matches a condition.
12. Difference Between forEach
and map
forEach
:- Loops through the array.
- Doesn’t return anything (used for actions like logging).
map
:- Creates a new array by applying a function to each element.
13. What is a Callback Function?
A callback function is a function that is passed as an argument to another function. It is called (or executed) after the completion of the task in the main function.
Use Cases of Callback Functions:
1. Asynchronous Programming: Handling tasks that take time, like fetching data from a server.
setTimeout(() => {
console.log(“Task completed after 2 seconds!”);
}, 2000);
2. Event Handling: Executing a function when a button is clicked.
button.addEventListener(“click”, () => {
console.log(“Button clicked!”);
});
3. Array Operations: Using callbacks with methods like map
, filter
, or forEach
.
const numbers = [1, 2, 3];
numbers.forEach((num) => {
console.log(num * 2);
});
4. Error Handling: Managing success and error conditions.
function fetchData(callback) {
const data = “Success!”;
callback(null, data);
}
fetchData((err, data) => {
if (err) console.error(err);
else console.log(data);
});
14. What is Callback Hell?
Callback Hell is a situation where multiple nested callback functions make the code:
- Hard to read.
- Difficult to debug.
- Challenging to maintain.
Example of Callback Hell:
getData((data) => {
processData(data, (processedData) => {
saveData(processedData, (result) => {
console.log(“Data saved successfully!”);
});
});
});
How to Avoid Callback Hell:
1. Use Promises: Promises help to chain asynchronous calls and avoid deep nesting.
getData()
.then(processData)
.then(saveData)
.then(() => console.log(“Data saved successfully!”))
.catch((error) => console.error(error));
2. Use Async/Await: Async/Await makes the code look synchronous and easier to read.
async function handleData() {
try {
const data = await getData();
const processedData = await processData(data);
await saveData(processedData);
console.log(“Data saved successfully!”);
} catch (error) {
console.error(error);
}
}
15. What is a Promise?
A Promise is an object in JavaScript that represents the result of an asynchronous operation. It can be in one of three states:
- Pending: Initial state, the operation hasn’t completed.
- Fulfilled: The operation completed successfully.
- Rejected: The operation failed.
Example of a Promise:
const fetchData = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve(“Data fetched successfully!”);
} else {
reject(“Error fetching data.”);
}
});
// Handling the Promise
fetchData
.then((result) => console.log(result)) // If resolved
.catch((error) => console.error(error)); // If rejected
Why Use Promises?
- To handle asynchronous code in a clean, manageable way.
- Avoids issues like callback hell.
- Enables chaining of actions with
.then()
and.catch()
.
Example with Promises and API Call:
fetch(“https://api.example.com/data”)
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(“Error:”, error));