Basic Questions
1. What is the difference between var, let, and const?
Answer:
var: Function-scoped, can be re-declaration is allowed, and it is hoisted.
let: Block-scoped, re-declaration is not allowed, but reassigning a value is possible.
const: Block-scoped, re-declaration is not allowed nor is reassigning of values.
var a = 10; // Function-scoped
let b = 20; // Block-scoped
const c = 30; // Block-scoped, reassigning not possible
2. Explain hoisting in JavaScript.
Answer:
Hoisting basically moves function and variable declarations to the top of their scope at compile time. Variables declared with var are hoisted but initialized with undefined, while let and const are hoisted but not initialized.
console.log(x); // undefined
var x = 10; // Hoisted
console.log(y); // ReferenceError
let y = 20;
3. What is a closure in JavaScript? Give an example.
Answer:
A closure is a function having access to the outer function’s scope even after the outer function has returned.
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
const counter = outer();
counter(); // 1
counter(); // 2
4. What are JavaScript data types?
Answer:
Primitive Types: String, Number, Boolean, Null, Undefined, Symbol, BigInt
Reference Types: Objects, Arrays, Functions
let str = "Hello"; // String
let num = 10; // Number
let isTrue = true; // Boolean
let obj = { name: "John" }; // Object
5. What's is the difference between == and ===?
Answer:
== The loose equality operator compares data after converting to the same data type.
=== Strict equality operator, identifies whether the value and its data type is similar or not.
console.log(5 == "5"); // true
console.log(5 === "5"); // false
Intermediate Questions
6. What is event delegation in JavaScript?
Answer:
Event delegation is a way to handle events on child elements at the parent element level. It improves performance.
document.getElementById("parent").addEventListener("click", function(event) {
if (event.target.tagName === "BUTTON") {
console.log("Button clicked:", event.target.textContent);
}
});
7. Explain callback functions with an example.
Answer:
A callback is a function passed as an argument to another function.
function greet(name, callback) {
console.log("Hello, " + name);
callback();
}
function sayGoodbye() {
console.log("Goodbye!");
}
greet("John", sayGoodbye);
8. What are Promises? Explain .then() and .catch().
Answer:
A Promise represents an asynchronous operation that may complete or fail.
let myPromise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Success!"), 1000);
});
myPromise.then(response => console.log(response)).catch(error => console.log(error));
9. What is the difference between setTimeout and setInterval?
Answer:
setTimeout(): Executes a function once after a specified delay.
setInterval(): Executes a function repeatedly at specified intervals.
setTimeout(() => console.log("Runs once"), 1000);
setInterval(() => console.log("Runs every second"), 1000);
10. What is the this keyword in JavaScript?
Answer:
In a function, this refers to the global object (window in browsers).
In an object method, this refers to the object itself.
const obj = {
name: "John",
greet() {
console.log(this.name);
}
};
obj.greet(); // "John"
Advanced Questions
11. Explain prototypal inheritance?
Answer:
Objects inherit properties and methods from their prototypes.
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log("Hello, " + this.name);
};
const john = new Person("John");
john.greet(); // "Hello, John"
12. What is the difference between apply(), call(), and bind()?
Answer:
call(): Calls a function with a given this value and arguments.
apply(): Similar to call(), but the arguments are in an array form.
bind(): Returns a new function with this bound.
const person = { name: "John" };
function greet(city) {
console.log(`Hello, I am ${this.name} from ${city}`);
}
greet.call(person, "NY"); // Using call
greet.apply(person, ["NY"]); // Using apply
const boundFunc = greet.bind(person, "NY");
boundFunc(); // Using bind
13. What is memoization in JavaScript?
Answer:
Memoization - caching the results of a function execution to use it further for performance enhancement.
function memoizedAdd() {
let cache = {};
return function (num) {
if (num in cache) return cache[num];
cache[num] = num + 10;
return cache[num];
};
}
const add = memoizedAdd();
console.log(add(10)); // 20
console.log(add(10)); // Cached 20
14. Explain CORS (Cross-Origin Resource Sharing).
Answer:
CORS is a concept that allows/disallows requests from other origins to avoid some security-related issues.
Access-Control-Allow-Origin: *
15. What is service workers?
Answer:
Service workers run in the background and enable features like caching, push notifications, and offline support.
navigator.serviceWorker.register("/service-worker.js")
.then(reg => console.log("Service Worker registered", reg))
.catch(err => console.log("Service Worker failed", err));