Skip to main content

20 Most Important JavaScript Questions and Answers

20 Most Important JavaScript Questions and Answers

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

Popular posts from this blog

How to Display Flash Messages in EJS using Node.js and Express

Displaying Flash Messages in EJS with Node.js and Express Flash messages are a great way to give users quick feedback — like "Login successful!" or "Please enter all fields!" . In this guide, you’ll learn how to implement them using: express-session connect-flash EJS templating ๐Ÿ“ฆ Step 1: Install Required Packages npm install express express-session connect-flash ejs ⚙️ Step 2: Setup Express App and Middleware const express = require('express'); const session = require('express-session'); const flash = require('connect-flash'); const app = express(); // Set view engine app.set('view engine', 'ejs'); // Middleware app.use(express.urlencoded({ extended: true })); app.use(session({ secret: 'yourSecretKey', resave: false, saveUninitialized: true })); app.use(flash()); // Make flash messages available to all views app.use((req, res, next) => { res.lo...

Realtime Device Tracker using Node.js, Socket.IO & Leaflet

Realtime Device Tracker using Node.js, Socket.IO & Leaflet In this tutorial, you’ll learn how to build a realtime location tracking application that uses the browser’s GPS, Socket.IO for live communication, and Leaflet.js to display users on a map. ๐Ÿš€ Project Overview Backend: Node.js, Express.js, Socket.IO Frontend: HTML, Leaflet.js, Socket.IO client Features: Live GPS tracking, multi-user map, disconnect cleanup ๐Ÿ“ Folder Structure project-root/ ├── app.js ├── package.json ├── src/ │ ├── public/ │ │ ├── css/ │ │ │ └── style.css │ │ └── js/ │ │ └── script.js │ ├── routes/ │ │ └── routers.js │ ├── socket/ │ │ └── socketHandler.js │ └── views/ │ └── index.ejs ๐Ÿง  How It Works Each user shares their location using the browser's navigator.geolocation API. Location is sent to the server via Socket.IO . The server broadcasts each user’s position to all clien...

How to Send Emails in Node.js using Nodemailer and Ethereal

How to Send Email in Node.js using Nodemailer Email functionality is essential in modern web applications. Whether you're sending confirmation emails, password resets, or notifications, Node.js with Nodemailer makes this simple. In this blog, we'll walk through setting up email sending using Node.js , Express , and Ethereal Email for testing. ๐Ÿงพ Prerequisites Node.js installed Basic knowledge of Express.js Internet connection ๐Ÿ“ Project Structure project-folder/ ├── index.js ├── .env ├── package.json └── app/ └── controller/ └── emailSendController.js ๐Ÿ“ฆ Step 1: Install Dependencies npm init -y npm install express nodemailer dotenv npm install --save-dev nodemon ๐Ÿ” Configure nodemon (Optional but Recommended) Update your package.json with a custom start script: "scripts": { "start": "nodemon index.js" } ๐Ÿ” Step 2: Create a .env File Create a .env file a...