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 possible2. 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(); // 24. 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" }; // Object5. 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"); // falseIntermediate 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);
}
});