Struggle with Javascript interview? Top JS interview is here

Prepare for your next JavaScript interview with these 20 essential questions covering basics to advanced concepts. Includes code snippets, hoisting, closures, promises, and more!


1. How Can We Insert JavaScript Code?

JavaScript is embedded in HTML using the <script> tag. Typically, it can be placed in either the <head> or <body>However, the best practice is to load it just before the closing </body> tag because this ensures better page performanc

Example:

<script>
  document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>

 Best Practice: Specifically, place scripts at the bottom of <body> so that DOM elements are fully loaded before script execution. As a result, this prevents potential errors where JavaScript tries to access elements that haven’t been rendered yet.


2. How Does JavaScript Display Data?

JavaScript can output data in multiple ways:

MethodDescriptionExample
innerHTMLModifies HTML contentelement.innerHTML = "New Content"
document.write()Writes directly to HTML (avoid in production)document.write("Hello")
window.alert()Shows an alert boxalert("Warning!")
console.log()Logs to browser consoleconsole.log("Debugging")

3. What Are JavaScript Data Types?

JavaScript has primitive and non-primitive (reference) data types:

Primitive Types:

  • String ("Hello")
  • Number (42, 3.14)
  • Boolean (true, false)
  • Undefined (let a;)
  • Null (let b = null;)
  • Symbol (const sym = Symbol('id'))
  • BigInt (9007199254740991n)

Non-Primitive Types:

  • Object ({})
  • Array ([])
  • Function (function() {})

4. What Are the Different Variables in JavaScript?

JavaScript has var, let, and const for variable declaration.

Featurevarletconst
ScopeFunction-scopedBlock-scopedBlock-scoped
Re-declarationAllowedNot allowedNot allowed
ReassignmentAllowedAllowedNot allowed

Example:

var x = 10;  
x = 20; // Allowed  

let y = 30;  
y = 40; // Allowed  

const z = 50;  
z = 60; // Error (Cannot reassign const)  

5. What Is JavaScript Hoisting?

Hoisting moves variable and function declarations to the top of their scope before execution.

Hoisting with var:

console.log(a); // undefined (declaration hoisted)  
var a = 10;  
console.log(a); // 10  

Hoisting with let & const:

console.log(b); // ReferenceError (Temporal Dead Zone)  
let b = 20;  

6. Difference Between == and ===?

  • == checks value only (loose equality).
  • === checks value + type (strict equality).

Example:

console.log(5 == "5");  // true (type coercion)  
console.log(5 === "5"); // false (different types)  

7. What Are JavaScript Number Methods?

MethodDescriptionExample
toString()Converts number to string(10).toString()"10"
toFixed(2)Rounds to 2 decimal places3.1415.toFixed(2)"3.14"
toExponential()Exponential notation1000.toExponential()"1e+3"
parseInt()Converts string to integerparseInt("10.5")10

8. Is JavaScript Statically or Dynamically Typed?

JavaScript is dynamically typed—variables can change types at runtime.

Example:

let value = 42;       // Number  
value = "Hello";      // Now a String  
value = true;         // Now a Boolean  

9. What Is NaN in JavaScript?

NaN (Not-a-Number) represents an invalid number.

Key Points:

  • typeof NaN"number"
  • NaN === NaNfalse (Use isNaN() instead)

Example:

console.log(0 / 0);          // NaN  
console.log(Math.sqrt(-1));  // NaN  
console.log(isNaN(NaN));     // true  

10. Important String Methods in JavaScript

MethodDescriptionExample
slice(1, 4)Extracts substring"Hello".slice(1,4)"ell"
split(",")Splits into array"a,b,c".split(",")["a","b","c"]
toUpperCase()Converts to uppercase"hello".toUpperCase()"HELLO"
includes("JS")Checks substring"JavaScript".includes("JS")true

Advanced JavaScript Questions

11. What Are Closures and How Do They Work?

closure is a function that remembers its lexical scope even when executed outside it.

Practical Use Cases:

  • Data Privacy (Module Pattern)
  • Currying & Partial Applications
  • Memoization (Caching)

Example:

function outer() {
  let count = 0;
  return function inner() {
    return ++count;
  };
}

const counter = outer();
console.log(counter()); // 1  
console.log(counter()); // 2  

 Explanation:

  • inner() retains access to count even after outer() finishes execution

12. Explain this Keyword

this refers to the object it belongs to.

Example:

const person = {
  name: "John",
  greet: function() {
    console.log(`Hello, ${this.name}!`);
  }
};
person.greet(); // "Hello, John!"  

13. What Are Promises?

Promises handle asynchronous operations.

Example:

const fetchData = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Data fetched!"), 1000);
});
fetchData.then(data => console.log(data)); // "Data fetched!"  

14. How Does async/await Work Under the Hood?

async/await is syntactic sugar over Promises.

Behind the Scenes:

await pauses execution until the Promise resolves.

An async function always returns a Promise.

Example:

async function fetchData() {
  const response = await fetch("https://api.example.com/data");
  const data = await response.json();
  return data;
}

// Equivalent to:
function fetchData() {
  return fetch("https://api.example.com/data")
    .then(response => response.json());
}

🔹 Key Insight:

  • await can only be used inside async functions.
  • Error handling requires try/catch.

15. What Is Event Bubbling?

Events propagate from child to parent.

Example:

document.querySelector("#child").addEventListener("click", () => {
  console.log("Child clicked!");
});
document.querySelector("#parent").addEventListener("click", () => {
  console.log("Parent clicked!"); // Also triggers if child is clicked
});

16. What Is the Temporal Dead Zone (TDZ)?

The TDZ is the period where let and const variables exist but are uninitialized.

Example:

console.log(x); // ❌ ReferenceError (TDZ)  
let x = 10;  

Why?

  • var is hoisted and initialized with undefined.
  • let/const are hoisted but not initialized until declaration.


17. What Is Memoization?

Memoization caches function results to avoid redundant computations.

Example:

function memoize(fn) {
  const cache = {};
  return function(...args) {
    const key = JSON.stringify(args);
    if (cache[key]) return cache[key];
    return (cache[key] = fn(...args));
  };
}

const factorial = memoize(n => (n <= 1) ? 1 : n * factorial(n - 1));
console.log(factorial(5)); // 120 (cached)  

18. What Is the Difference Between callapply, and bind?

All three methods allow explicit this binding, but differ in usage:

MethodSyntaxInvocation
callfn.call(this, arg1, arg2)Immediately invoked
applyfn.apply(this, [args])Immediately invoked (takes array)
bindconst boundFn = fn.bind(this)Returns a new function

Example:

const user = { name: "Alice" };  

function greet(greeting, punctuation) {
  return `${greeting}, ${this.name}${punctuation}`;
}

console.log(greet.call(user, "Hi", "!"));        // "Hi, Alice!"  
console.log(greet.apply(user, ["Hello", "."]));  // "Hello, Alice."  

const boundGreet = greet.bind(user, "Hey");
console.log(boundGreet("?"));  // "Hey, Alice?"  

19. Explain Prototypal Inheritance in JavaScript

JavaScript uses prototypes instead of classical inheritance.

Key Concepts:

  • Every object has a __proto__ property pointing to its prototype.
  • Functions have a prototype property used when called with new.

Example:

function Person(name) {
  this.name = name;
}

Person.prototype.greet = function() {
  return `Hello, ${this.name}!`;
};

const john = new Person("John");
console.log(john.greet()); // "Hello, John!"  

20. What Is the Event Loop in JavaScript?

The Event Loop is what allows JavaScript to handle asynchronous operations despite being single-threaded.

How It Works:

  1. Call Stack – Executes synchronous code.
  2. Web APIs – Handle async tasks (setTimeoutfetch).
  3. Callback Queue – Stores callbacks from Web APIs.
  4. Event Loop – Moves callbacks from the queue to the stack when the stack is empty.

Example:

console.log("Start");  

setTimeout(() => console.log("Timeout"), 0);  

Promise.resolve().then(() => console.log("Promise"));  

console.log("End");  

// Output:  
// Start  
// End  
// Promise  
// Timeout  

Why?

  • setTimeout goes to the Callback Queue.
  • Promise goes to the Microtask Queue (higher priority).
  • The Event Loop processes microtasks before callbacks.

Conclusion

These 20 JavaScript interview questions cover fundamental to advanced topics, helping you prepare for technical interviews.

🔗 Further Reading:

🚀 Practice these concepts to ace your next interview!


Suggested Resources:


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top