This blog post covers 20 essential JavaScript questions and answers with short code examples to solidify your understanding and help in interviews or practice.
1. What is JavaScript?
JavaScript is a scripting language used to build dynamic and interactive web pages in browsers.
console.log("Hello, JavaScript!");
2. What are the data types in JavaScript?
There are two types:
- Primitive:
String,Number,Boolean,Null,Undefined,Symbol,BigInt - Non-Primitive:
Object,Array,Function
3. Difference between var, let, const?
var is function-scoped and hoisted. It can be redeclared and updated.
let is block-scoped and not hoisted to the top. It can be updated but not redeclared in the same scope.
const is block-scoped, cannot be updated or redeclared.
function test() {
if (true) {
var a = 1;
let b = 2;
const c = 3;
}
console.log(a); // ✅ accessible
// console.log(b); ❌ ReferenceError
// console.log(c); ❌ ReferenceError
}
test();
4. What is a closure?
A closure is when a function remembers its outer scope even after it has returned.
function outer() {
let count = 0;
return function() {
count++;
return count;
};
}
let counter = outer();
console.log(counter()); // 1
5. Difference between == and ===?
== compares value, === compares value and type.
console.log(5 == "5"); // true
console.log(5 === "5"); // false
6. What is hoisting?
Hoisting is JavaScript’s default behavior of moving declarations to the top of the current scope before code execution. Only declarations are hoisted—not initializations.
console.log(a); // undefined
var a = 10;
console.log(b); // ReferenceError
let b = 20;
7. What is the event loop?
JavaScript has a single-threaded event loop that allows async tasks (like timers, API calls) to be queued and executed after the current call stack is clear. It ensures non-blocking behavior.
console.log("Start");
setTimeout(() => console.log("Async!"), 0);
console.log("End");
// Output:
// Start
// End
// Async!
8. What are arrow functions?
Shorter syntax and lexical this binding.
const greet = name => `Hello, ${name}`;
console.log(greet("Rana"));
9. Explain async/await.
Async functions simplify working with promises and make code cleaner and easier to read.
async function getData() {
let res = await fetch("https://api.example.com");
let data = await res.json();
console.log(data);
}
getData();
10. What is a Promise?
A Promise represents the result of an async operation. It can be:
pending, fulfilled, or rejected. You handle it using .then() and .catch().
const task = new Promise((resolve, reject) => {
let success = true;
success ? resolve("Success") : reject("Error");
});
task.then(res => console.log(res))
.catch(err => console.log(err));
11. What is the DOM?
The DOM (Document Object Model) is a programming interface for HTML and XML documents. It represents the page as a tree so programs can read, access, and modify elements.
document.getElementById("demo").innerText = "Updated text!";
12. What is event delegation?
Event delegation is a technique where you attach a single event listener to a parent element to manage events from its children, especially useful when children are added dynamically.
document.getElementById("list").addEventListener("click", function(e) {
if (e.target.tagName === "LI") {
alert("Clicked: " + e.target.textContent);
}
});
13. Difference between null and undefined?
null: assigned by the programmer to indicate no value.undefined: default value of an uninitialized variable.
let a;
let b = null;
console.log(a); // undefined
console.log(b); // null
14. Explain this keyword.
this refers to the context from which the function was called.
const person = {
name: "Rana",
greet() {
console.log(this.name);
}
};
person.greet(); // Rana
15. Difference between map() and forEach()?
map() creates and returns a new array with modified items.
forEach() simply executes a function on each item and returns undefined.
let arr = [1, 2, 3];
let mapped = arr.map(x => x * 2); // [2, 4, 6]
arr.forEach(x => console.log(x)); // 1 2 3
16. What is debouncing?
Debouncing prevents a function from running too often. Useful in scroll, search, or resize events to optimize performance.
function debounce(func, delay) {
let timeout;
return function() {
clearTimeout(timeout);
timeout = setTimeout(func, delay);
};
}
const onSearch = debounce(() => {
console.log("Searching...");
}, 300);
17. What is a callback function?
A function passed to another function to be executed later.
function greet(name, callback) {
console.log("Hi " + name);
callback();
}
greet("Rana", () => console.log("Callback fired"));
18. What are template literals?
Template literals use backticks (``) and allow string interpolation using ${}. They also support multi-line strings.
let name = "Rana";
console.log(`Hello, ${name}!`);
19. How do you clone an object?
You can create a shallow copy using the spread operator or Object.assign().
let original = { name: "Rana", age: 30 };
let copy1 = { ...original };
let copy2 = Object.assign({}, original);
console.log(copy1, copy2);
20. What is the use of setTimeout and setInterval?
setTimeout(): runs a function once after a delay.setInterval(): runs a function repeatedly after intervals.
setTimeout(() => console.log("Run once"), 1000);
setInterval(() => console.log("Repeat every 2s"), 2000);
✅ Conclusion
Understanding these JavaScript questions gives you a strong foundation for web development and interviews.
“Code daily. Write. Break. Learn. Repeat.” – A JavaScript Learner
Explore more at thelearnwithrana.blogspot.com – tutorials, blogs, and career tips.
Comments
Post a Comment