Javascript Interview Questions – Set 1

1. What is JavaScript and how does it differ from Java?

Answer: JavaScript is a high-level, dynamically typed, and interpreted programming language primarily used for building interactive web pages. Despite the similar name, JavaScript and Java are entirely different languages. The key differences include:

  • JavaScript is primarily used for client-side web development, while Java can be used for various purposes, including web development, desktop applications, and server-side applications.
  • JavaScript is an interpreted language, executed in web browsers, whereas Java is compiled and executed on the Java Virtual Machine (JVM).
  • JavaScript is dynamically typed, meaning variable types can change during runtime, whereas Java is statically typed, requiring variable types to be declared explicitly.

2. Explain the difference between null and undefined in JavaScript.

Answer:

  • null is an intentional absence of any object value. It represents a deliberate lack of value.
  • undefined is a primitive value that indicates a variable has been declared but hasn’t been assigned any value yet.
JavaScript
   let x = null;       // x has a null value
   let y;              // y is undefined as it's not assigned a value

3. What is a closure in JavaScript, and why is it useful?

Answer: A closure is a function bundled with its lexical environment (the set of variables it can access). It allows a function to remember and access its outer function’s scope, even after the outer function has finished executing. Closures are useful for:

  • Implementing data encapsulation and creating private variables.
  • Managing state in asynchronous code.
  • Implementing modules and maintaining encapsulation in JavaScript.
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

4. Explain the event delegation pattern in JavaScript.

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 beneficial for performance and memory efficiency. Here’s an example:

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>

5. What is the difference between let, const, and var for variable declaration in JavaScript?

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, whereas let and var can.
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

6. Explain the concept of hoisting in JavaScript.

Answer: Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during compilation. However, only declarations are hoisted, not initializations.

JavaScript
   console.log(x); // undefined (variable is hoisted)
   var x = 10;

   greet(); // Hello (function is hoisted)
   function greet() {
     console.log("Hello");
   }

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

Answer:

  • == (loose equality) checks for equality of values with type coercion, meaning it can convert operands to the same type before comparison.
  • === (strict equality) checks for equality of values without type coercion; it requires both the value and type to be the same.
JavaScript
   5 == "5"   // true (loose equality, type coercion)
   5 === "5"  // false (strict equality, different types)

8. Explain the concept of the event loop in JavaScript and how it handles asynchronous operations.

Answer: The event loop is a core part of JavaScript’s concurrency model. It handles asynchronous operations by constantly checking the message queue for tasks and executing them one at a time, in order. This allows JavaScript to be non-blocking and handle tasks like callbacks, promises, and async/await.

JavaScript
   console.log("Start");

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

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

9. What is a promise in JavaScript, and how does it work?

Answer: A promise is an object representing the eventual completion or failure of an asynchronous operation. It has states (pending, fulfilled, or rejected) and can be used to handle asynchronous code in a more readable and manageable way.

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);
     });

10. What is the purpose of the bind, call, and apply methods in JavaScript?

Answer: These methods are used to manipulate the value of this in a function:

  • bind: Creates a new function with a specified this value but does not call the function immediately.
  • call: Calls a function with a specified this value and arguments passed individually.
  • apply: Calls a function with a specified this value and arguments passed as an array.
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

11. What is the difference between map, filter, and reduce in JavaScript?

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. What is the difference between == and === in JavaScript, and when should you use each one?

Answer:

  • == (loose equality) compares values after type coercion. It converts operands to the same type before comparison, which can lead to unexpected results.
  • === (strict equality) compares values without type coercion. It requires both the value and type to be the same. It is generally recommended to use === for most comparisons to avoid unexpected type coercion issues.
JavaScript
   5 == "5"   // true (loose equality, type coercion)
   5 === "5"  // false (strict equality, different types)

13. What is the event loop in JavaScript, and how does it work with the call stack and the callback queue?

Answer:
The event loop is a critical part of JavaScript’s asynchronous execution model. It works with the call stack and callback queue as follows:

  • The call stack is a data structure that tracks the execution of synchronous code. Functions are pushed onto the stack when they are called and popped off when they return.
  • The callback queue stores asynchronous tasks (such as callbacks from timers or I/O operations) once they are complete and ready to be executed.
  • The event loop continuously checks the call stack and the callback queue. If the call stack is empty, it takes the first task from the callback queue and pushes it onto the call stack for execution. This mechanism allows JavaScript to handle asynchronous operations without blocking the main thread, ensuring that the UI remains responsive.

14. Explain the concept of the this keyword in JavaScript and how it behaves in different contexts.

Answer:
The this keyword in JavaScript refers to the current execution context or the object that the function is operating on. The value of this can vary depending on how a function is called:

  • In the global context, this refers to the global object (e.g., window in a browser, global in Node.js).
  • In a function that is not part of an object, this refers to the global object as well.
  • In a method (a function within an object), this refers to the object that owns the method.
  • In an event handler, this typically refers to the DOM element that triggered the event. You can also explicitly set the value of this using methods like call(), apply(), or bind().
JavaScript
   const person = {
     name: "John",
     greet: function() {
       console.log(`Hello, ${this.name}`);
     }
   };

   person.greet(); // "Hello, John"

15. What is the difference between null and undefined in JavaScript, and when should you use each one?

Answer:

  • null represents the intentional absence of any object value. It is typically used to signify that a variable or object property should have no value.
  • undefined represents the absence of a value due to the absence of a variable or the lack of assignment. It is the default value for uninitialized variables and function parameters. Generally, you should use null when you want to explicitly indicate that a variable or object property has no meaningful value, and use undefined when a variable or property hasn’t been assigned a value yet.
JavaScript
   let x = null;       // x has a null value (explicitly set)
   let y;              // y is undefined (not assigned a value)

Leave a Comment

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

Scroll to Top