Common 30 Javascript interview questions with solutions

 Here is a comprehensive list of 100 common JavaScript interview questions with solutions. These cover a wide range of topics from basic JavaScript concepts to more advanced ones.

1. What is JavaScript?

Answer: JavaScript is a high-level, dynamic programming language that is widely used for building interactive web pages and web applications. It is the scripting language that runs in the browser, and it is also used for server-side development (Node.js).


2. What are the different data types in JavaScript?

Answer: JavaScript has 7 basic data types:

  • Primitive types: undefined, null, boolean, number, string, symbol, bigint
  • Reference type: object

3. What is the difference between == and === in JavaScript?

Answer:

  • == (Equality Operator): Compares values after converting them to the same type (type coercion).
  • === (Strict Equality Operator): Compares both value and type without type conversion.
javascript
0 == '0'; // true 0 === '0'; // false

4. Explain "hoisting" in JavaScript.

Answer: Hoisting is JavaScript's behavior of moving declarations to the top of the current scope before code execution. Variables and functions are hoisted but only their declarations, not their initializations.

javascript
console.log(x); // undefined var x = 5; foo(); // "Hello" function foo() { console.log("Hello"); }

5. What are closures in JavaScript?

Answer: A closure is a function that remembers its lexical scope, even when the function is executed outside that scope.

javascript
function outer() { var outerVar = "I am outer"; return function inner() { console.log(outerVar); } } var closureFunc = outer(); closureFunc(); // "I am outer"

6. What is the this keyword in JavaScript?

Answer: The this keyword refers to the object from which a function is called. Its value depends on the context in which the function is invoked.

javascript
var person = { name: 'Alice', greet: function() { console.log(this.name); } }; person.greet(); // "Alice"

7. What is the event delegation in JavaScript?

Answer: Event delegation is a technique where you attach a single event listener to a parent element rather than attaching listeners to individual child elements. This is more efficient, especially for dynamic content.

javascript
document.getElementById('parent').addEventListener('click', function(event) { if (event.target && event.target.matches('button.classname')) { console.log('Button clicked!'); } });

8. What are promises in JavaScript?

Answer: A Promise is an object that represents the eventual completion or failure of an asynchronous operation. It has three states: pending, fulfilled, and rejected.

javascript
let promise = new Promise((resolve, reject) => { let success = true; if (success) { resolve('Success!'); } else { reject('Error!'); } }); promise.then(result => console.log(result)).catch(error => console.log(error));

9. Explain async/await in JavaScript.

Answer: async/await is a modern syntax for working with Promises, making asynchronous code easier to read and write. async functions return a Promise, and await can be used to pause execution until the Promise resolves.

javascript
async function fetchData() { let response = await fetch('https://api.example.com'); let data = await response.json(); console.log(data); }

10. What is the difference between null and undefined in JavaScript?

Answer:

  • null is an intentional assignment of no value, representing the absence of any object value.
  • undefined is the default value of variables that have not been assigned a value or function parameters that are not provided.
javascript
var a; // undefined var b = null; // null

11. What are arrow functions in JavaScript?

Answer: Arrow functions provide a shorter syntax for writing functions and do not have their own this context (they inherit this from the outer function).

javascript
const sum = (a, b) => a + b; console.log(sum(2, 3)); // 5

12. What is the spread operator in JavaScript?

Answer: The spread operator (...) is used to expand elements of an iterable (like arrays or objects) into individual elements or properties.

javascript
const arr = [1, 2, 3]; const newArr = [...arr, 4, 5]; // [1, 2, 3, 4, 5] const obj = { a: 1, b: 2 }; const newObj = { ...obj, c: 3 }; // { a: 1, b: 2, c: 3 }

13. What is the bind() method in JavaScript?

Answer: The bind() method creates a new function that, when called, has its this keyword set to the provided value. It also allows you to prepend arguments to the function.

javascript
const obj = { name: 'Alice' }; function greet(greeting) { console.log(`${greeting}, ${this.name}`); } const greetAlice = greet.bind(obj); greetAlice('Hello'); // "Hello, Alice"

14. What is destructuring in JavaScript?

Answer: Destructuring is a syntax that allows you to extract values from arrays or objects and assign them to variables.

javascript
// Array Destructuring const [a, b] = [1, 2]; // a = 1, b = 2 // Object Destructuring const person = { name: 'Alice', age: 25 }; const { name, age } = person; // name = 'Alice', age = 25

15. What is the setTimeout() function in JavaScript?

Answer: setTimeout() is a JavaScript function that executes a specified function after a certain delay.

javascript
setTimeout(() => { console.log('Executed after 2 seconds'); }, 2000);

16. What is the setInterval() function in JavaScript?

Answer: setInterval() is a JavaScript function that repeatedly calls a function with a fixed time delay between each call.

javascript
setInterval(() => { console.log('Executed every 2 seconds'); }, 2000);

17. What is a callback function in JavaScript?

Answer: A callback function is a function that is passed as an argument to another function and is executed after some kind of event or asynchronous operation is completed.

javascript
function greeting(callback) { console.log('Hello'); callback(); } function sayBye() { console.log('Goodbye'); } greeting(sayBye); // "Hello" "Goodbye"

18. What are higher-order functions in JavaScript?

Answer: Higher-order functions are functions that take one or more functions as arguments, return a function, or both.

javascript
function add(a, b) { return a + b; } function applyOperation(a, b, operation) { return operation(a, b); } console.log(applyOperation(5, 3, add)); // 8

19. What is localStorage in JavaScript?

Answer: localStorage is a built-in JavaScript object that allows you to store data in the browser persistently, even after the browser is closed.

javascript
localStorage.setItem('name', 'Alice'); console.log(localStorage.getItem('name')); // "Alice"

20. What is sessionStorage in JavaScript?

Answer: sessionStorage is similar to localStorage, but its data is only available for the duration of the page session.

javascript
sessionStorage.setItem('name', 'Bob'); console.log(sessionStorage.getItem('name')); // "Bob"

21. What is JSON.parse() and JSON.stringify() in JavaScript?

Answer:

  • JSON.parse() converts a JSON string into a JavaScript object.
  • JSON.stringify() converts a JavaScript object into a JSON string.
javascript
const jsonString = '{"name": "Alice"}'; const obj = JSON.parse(jsonString); // { name: 'Alice' } const jsonStringified = JSON.stringify(obj); // '{"name": "Alice"}'

22. What is the typeof operator in JavaScript?

Answer: The typeof operator returns a string indicating the type of the operand.

javascript
typeof 'hello'; // 'string' typeof 42; // 'number' typeof true; // 'boolean' typeof {}; // 'object'

23. What is the difference between call(), apply(), and bind() in JavaScript?

Answer:

  • call() and apply() are used to invoke a function with a specified this value.
  • call() takes arguments individually.
  • apply() takes arguments as an array or array-like object.
  • bind() returns a new function with the specified this value and arguments.
javascript
const obj = { name: 'Alice' }; function greet(greeting) { console.log(`${greeting}, ${this.name}`); } greet.call(obj, 'Hello'); // "Hello, Alice" greet.apply(obj, ['Hello']); // "Hello, Alice" const greetAlice = greet.bind(obj); greetAlice('Hello'); // "Hello, Alice"

24. What is NaN in JavaScript?

Answer: NaN stands for "Not-a-Number" and is a special value in JavaScript indicating that a value is not a valid number.

javascript
console.log(0 / 0); // NaN

25. Explain the difference between forEach() and map() in JavaScript.

Answer:

  • forEach() is used to iterate over an array and execute a function for each element but does not return anything.
  • map() is used to iterate over an array and return a new array of the same length with transformed values.
javascript
const arr = [1, 2, 3]; arr.forEach(num => console.log(num)); // 1 2 3 const newArr = arr.map(num => num * 2); // [2, 4, 6]

26. What are template literals in JavaScript?

Answer: Template literals are string literals that allow embedded expressions, multiline strings, and variable interpolation using ${}.

javascript
const name = 'Alice'; console.log(`Hello, ${name}`); // "Hello, Alice"

27. What is the difference between var, let, and const in JavaScript?

Answer:

  • var has function scope and can be redeclared.
  • let has block scope and can be reassigned.
  • const has block scope and cannot be reassigned.
javascript
var a = 1; let b = 2; const c = 3; a = 4; // allowed b = 5; // allowed c = 6; // error: Assignment to constant variable.

28. What is NaN and how do you check if a value is NaN?

Answer: NaN (Not a Number) is a special value in JavaScript. You can check if a value is NaN using Number.isNaN().

javascript
console.log(Number.isNaN(NaN)); // true console.log(Number.isNaN(5)); // false

29. What is the difference between synchronous and asynchronous JavaScript?

Answer:

  • Synchronous JavaScript: Code is executed line-by-line, and the program waits for each line to finish before moving to the next.
  • Asynchronous JavaScript: Code is executed without blocking the program, allowing the program to run other operations while waiting for tasks like network requests or file reading.
javascript
// Synchronous console.log('A'); console.log('B'); // Asynchronous setTimeout(() => console.log('C'), 0); console.log('D');

30. Explain the concept of event loop in JavaScript.

Answer: The event loop is the mechanism that allows JavaScript to perform non-blocking I/O operations by offloading operations to the system kernel. The event loop continuously checks the message queue and pushes the tasks to the stack.


I hope this list gives you a solid foundation for your JavaScript interview preparation! Would you like more examples or explanations for specific questions? Let me know!

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

oAuth in angular