Javascript Interview Questions – Set 2

1. What is the difference between null and undefined in JavaScript? When should you use each one, and how can you check for them?

Answer:

  • null is a deliberate absence of value and is typically used to indicate that a variable or object property should have no value.
  • undefined signifies the absence of value due to the absence of a variable or the lack of assignment. It is the default value for uninitialized variables and function parameters. You can check for null using strict equality (===) and undefined using the typeof operator or strict equality. For example:
JavaScript
   let x = null;
   let y;

   if (x === null) {
     // Handle null value
   }

   if (typeof y === 'undefined') {
     // Handle undefined value
   }

2. Explain the concept of prototypal inheritance in JavaScript. How does it differ from classical inheritance?

Answer:
Prototypal inheritance is a mechanism in JavaScript where objects can inherit properties and methods from other objects through their prototype chain. Each object has a prototype, and when a property or method is accessed on an object, JavaScript looks up the chain to find it.

This differs from classical inheritance (used in languages like Java and C++) where classes define the blueprint for objects, and objects are instances of classes. In JavaScript, objects can directly inherit from other objects without the need for classes.

JavaScript
   function Animal(name) {
     this.name = name;
   }

   Animal.prototype.makeSound = function() {
     console.log('Generic animal sound');
   };

   function Dog(name) {
     Animal.call(this, name);
   }

   Dog.prototype = Object.create(Animal.prototype);

   const myDog = new Dog('Buddy');
   myDog.makeSound(); // "Generic animal sound"

3. What is a callback function in JavaScript, and why is it important in asynchronous programming?

Answer:
A callback function is a function that is passed as an argument to another function and is executed after the completion of the parent function or some other event. Callbacks are essential in asynchronous programming to handle tasks like handling responses from APIs, reading files, or executing code after a timer expires.

JavaScript
   function fetchData(callback) {
     setTimeout(function() {
       const data = 'Some data';
       callback(data);
     }, 1000);
   }

   fetchData(function(data) {
     console.log(data);
   });

4. Explain the differences between let, const, and var in terms of scope, hoisting, and reassignment.

Answer:

  • let and const are block-scoped, meaning they are limited to the block they are declared in, while var is function-scoped.
  • const variables cannot be reassigned after declaration, while let and var can.
  • Variables declared with var are hoisted, meaning their declarations are moved to the top of their containing function or global scope, while let and const are not hoisted.
JavaScript
   let x = 10;
   const y = 20;
   var z = 30;

   if (true) {
     let x = 5; // Creates a new block-scoped 'x'
     const y = 15; // Creates a new block-scoped 'y'
     var z = 25; // Modifies the existing 'z'
   }

   console.log(x); // 10
   console.log(y); // 20
   console.log(z); // 25

5. What is a closure in JavaScript, and why is it useful? Provide an example.

Answer:
A closure is a function that has access to its own scope, the outer function’s scope, and the global scope. Closures are useful for encapsulating behavior, maintaining private variables, and preserving the state of a function even after it has finished executing.

JavaScript
   function outer() {
     let x = 10;
     function inner() {
       console.log(x); // inner can access the 'x' variable from outer
     }
     return inner;
   }

   const closureFunc = outer();
   closureFunc(); // logs 10

6. What is event delegation in JavaScript, and why is it important in web development? Provide an example.

Answer:
Event delegation is a technique where you attach a single event listener to a common ancestor of multiple elements, instead of attaching listeners to each individual element. This is important for performance and memory efficiency, especially when dealing with a large number of elements, as it reduces the number of event listeners.

JavaScript
   <ul id="myList">
     <li>Item 1</li>
     <li>Item 2</li>
     <li>Item 3</li>
   </ul>

   <script>
     document.getElementById("myList").addEventListener("click", function(event) {
       if (event.target.tagName === "LI") {
         console.log(event.target.textContent);
       }
     });
   </script>

7. What is the purpose of the bind, call, and apply methods in JavaScript, and how do they differ?

Answer:

  • bind: Creates a new function with a specified this value and optional arguments. It doesn’t call the function immediately but returns a new function that can be executed later.
  • call: Calls a function with a specified this value and any number of arguments passed individually.
  • apply: Calls a function with a specified this value and arguments passed as an array. These methods are used to control the value of this in a function and to pass arguments when invoking functions.
JavaScript
   const person = { name: "John" };

   function sayHello() {
     console.log(`Hello, ${this.name}`);
   }

   const sayHelloToJohn = sayHello.bind(person);
   sayHelloToJohn(); // Hello, John

   sayHello.call(person); // Hello, John
   sayHello.apply(person); // Hello, John

8. What is the event loop in JavaScript, and how does it handle asynchronous operations? Explain with an example.

Answer:
The event loop is a core part of JavaScript’s concurrency model. It handles asynchronous operations by continuously checking the message queue for tasks and executing them one at a time in a non-blocking manner.

JavaScript
   console.log("Start");

   setTimeout(function() {
     console.log("Timeout");
   }, 1000);

   console.log("End");
   // Output: Start, End, Timeout

In this example, setTimeout schedules the "Timeout" message to be added to the message queue after 1000 milliseconds. While waiting for that time, the event loop continues executing other code, such as "Start" and "End", without blocking.

9. What is a promise in JavaScript, and how does it work? Provide an example of using promises.

Answer:
A promise is an object representing the eventual completion or failure of an asynchronous operation. It has three states: pending, fulfilled, or rejected. Promises are used for managing asynchronous code and improving readability.

JavaScript
   const fetchData = () => {
     return new Promise((resolve, reject) => {
       setTimeout(() => {
         resolve("Data fetched successfully");
       }, 1000);
     });
   };

   fetchData()
     .then((data) => {
       console.log(data);
     })
     .catch((error) => {
       console.error(error);
     });

In this example, fetchData returns a promise that resolves after 1000 milliseconds. We use .then() to handle the resolved value (data) and .catch() to handle any errors.

10. Explain how closures work in JavaScript, and provide an example.

Answer:
A closure is a function that “closes over” its surrounding lexical scope, allowing it to retain access to variables and values even after the outer function has finished executing. Closures are created when inner functions are defined inside outer functions.

JavaScript
   function outer() {
     let x = 10;
     function inner() {
       console.log(x); // inner can access the 'x' variable from outer
     }
     return inner;
   }

   const closureFunc = outer();
   closureFunc(); // logs 10

In this example, inner is a closure because it retains access to the x variable from the outer function, even after outer has finished executing.

11. What is the purpose of the map, filter, and reduce functions in JavaScript? Provide examples of each.

Answer:

  • map: Transforms each element of an array and returns a new array of the same length.
  • filter: Filters elements of an array based on a condition and returns a new array.
  • reduce: Reduces an array to a single value by applying a function to each element.
JavaScript
   const numbers = [1, 2, 3, 4, 5];

   const doubled = numbers.map((num) => num * 2); // [2, 4, 6, 8, 10]

   const even = numbers.filter((num) => num % 2 === 0); // [2, 4]

   const sum = numbers.reduce((acc, num) => acc + num, 0); // 15

12. Explain the difference between synchronous and asynchronous code in JavaScript. Provide examples of each.

Answer:

  • Synchronous code is executed in a sequential manner, one statement at a time, and blocks further execution until each statement is completed.
  • Asynchronous code allows tasks to be executed independently, and the program doesn’t wait for them to finish. Callbacks, promises, and async/await are common tools for handling asynchronous operations.
JavaScript
   // Synchronous code
   console.log("Start");
   for (let i = 0; i < 3; i++) {
     console.log(i);
   }
   console.log("End");

   // Asynchronous code
   console.log("Start");
   setTimeout(function() {
     console.log("Timeout");
   }, 1000);
   console.log("End");

In the asynchronous example, "Timeout" is logged after a delay of 1000 milliseconds while the program continues executing other statements.

13. Explain the concept of arrow functions in JavaScript, and how do they differ from regular functions?

Answer:
Arrow functions are a concise way to write functions in JavaScript, introduced in ES6. They differ from regular functions in a few key ways:

  • Arrow functions do not have their own this or arguments. They inherit these from the enclosing function.
  • They cannot be used as constructors (with new).
  • Arrow functions have shorter syntax and do not require the function keyword or return statement for single expressions.
JavaScript
   const regularFunc = function(x) {
     return x * 2;
   };

   const arrowFunc = (x) => x * 2;

14. What are template literals in JavaScript, and how do they work? Provide an example.

Answer:
Template literals (also known as template strings) are a way to create strings in JavaScript with embedded expressions using backticks (` `). Inside template literals, you can embed variables or expressions using ${}.

JavaScript
   const name = "John";
   const greeting = `Hello, ${name}!`;
   console.log(greeting); // "Hello, John!"

Template literals are more readable and versatile than traditional string concatenation.

15. What is the localStorage and sessionStorage in the Web Storage API? How do they differ?

Answer:

  • localStorage and sessionStorage are part of the Web Storage API and allow web applications to store key-value pairs in the user’s browser.
  • localStorage stores data with no expiration date, and the data persists across browser sessions and tabs.
  • sessionStorage stores data for a single browser session, and the data is cleared when the session ends (e.g., when the browser is closed).
JavaScript
   // Storing data in localStorage
   localStorage.setItem("username", "John");

   // Storing data in sessionStorage
   sessionStorage.setItem("sessionToken", "abc123");

Leave a Comment

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

Scroll to Top