Top 10 JavaScript Interview Questions

  • What is the difference between let, var, and const in JavaScript?
  • What is a closure in JavaScript?
  • What are promises in JavaScript?
  • What is the difference between null and undefined in JavaScript?
  • What is event delegation in JavaScript?
  • What is the difference between == and === in JavaScript?
  • Explain hoisting in JavaScript.
  • What is the this keyword in JavaScript?
  • What is the difference between setTimeout and setInterval?
  • What is the spread operator in JavaScript?
  •  

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

    Answer:

    • var: Declares a variable with function-scoped or globally scoped if declared outside a function. Variables declared with var can be re-declared and updated.
    • let: Declares a block-scoped variable that can be updated but not re-declared within the same scope.
    • const: Declares a block-scoped constant. Its value cannot be changed after initialization and cannot be re-declared.

    Example:

    javascript
    var x = 10; let y = 20; const z = 30; x = 15; // Allowed y = 25; // Allowed z = 35; // Error: Assignment to constant variable.

    2. What is a closure in JavaScript?

    Answer:

    A closure is a function that "remembers" its lexical environment, even after the function that created it has finished executing. This allows the closure to access variables from its outer function even after the outer function has returned.

    Example:

    javascript
    function outer() { let outerVar = "I am from outer function"; return function inner() { console.log(outerVar); // Closure accessing outer function's variable }; } const closureFunc = outer(); closureFunc(); // Output: "I am from outer function"

    3. What are promises in JavaScript?

    Answer:

    A promise is an object representing the eventual completion or failure of an asynchronous operation. It allows chaining with .then() for success and .catch() for errors.

    Example:

    javascript
    let promise = new Promise((resolve, reject) => { let isSuccess = true; if (isSuccess) { resolve("Operation was successful"); } else { reject("Operation failed"); } }); promise .then(result => console.log(result)) // Output: Operation was successful .catch(error => console.log(error)); // Output: Operation failed

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

    Answer:

    • null: Represents an intentionally empty or non-existent value. It's an object.
    • undefined: Represents a variable that has been declared but has not been assigned a value.

    Example:

    javascript
    let a = null; // a is explicitly set to null let b; // b is declared but not assigned, so it's undefined console.log(a); // Output: null console.log(b); // Output: undefined

    5. What is event delegation in JavaScript?

    Answer:

    Event delegation is a technique in JavaScript where you attach a single event listener to a parent element, instead of attaching event listeners to individual child elements. This is efficient as it leverages event bubbling to handle events.

    Example:

    javascript
    document.querySelector("#parent").addEventListener("click", function(event) { if (event.target && event.target.matches("button.className")) { console.log("Button clicked!"); } }); // Assuming there are multiple buttons inside #parent

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

    Answer:

    • == (Equality operator): Compares values for equality but performs type coercion if the values are of different types.
    • === (Strict equality operator): Compares both value and type without type coercion.

    Example:

    javascript
    console.log(5 == '5'); // true (coerces the string '5' to a number) console.log(5 === '5'); // false (different types, number vs string)

    7. Explain hoisting in JavaScript.

    Answer:

    Hoisting is JavaScript's default behavior of moving declarations to the top of their containing scope (function or global scope). Variables declared with var and functions are hoisted, but only the declaration, not the initialization.

    Example:

    javascript
    console.log(a); // Output: undefined (due to hoisting) var a = 5; console.log(a); // Output: 5 foo(); // Output: "Hello" function foo() { console.log("Hello"); }

    8. What is the this keyword in JavaScript?

    Answer:

    The this keyword refers to the current context or object the function is called on. The value of this depends on how the function is called:

    • Inside a regular function: this refers to the global object (in browser, it's window).
    • Inside an object method: this refers to the object.
    • Inside a constructor: this refers to the newly created object.
    • Arrow functions: this is lexically bound to the context in which the function is defined.

    Example:

    javascript
    const person = { name: "Alice", greet: function() { console.log(`Hello, ${this.name}`); } }; person.greet(); // Output: Hello, Alice const greetFunc = person.greet; greetFunc(); // Output: Hello, undefined (global context)

    9. What is the difference between setTimeout and setInterval?

    Answer:

    • setTimeout(): Executes a function once after a specified delay.
    • setInterval(): Repeatedly executes a function with a specified time delay between each call.

    Example:

    javascript
    setTimeout(() => { console.log("Executed after 2 seconds"); }, 2000); let counter = 0; let intervalId = setInterval(() => { counter++; console.log("Counter:", counter); if (counter === 5) clearInterval(intervalId); // Stop the interval after 5 iterations }, 1000);

    10. What is the spread operator in JavaScript?

    Answer:

    The spread operator (...) allows you to spread the elements of an array or object into a new array or object.

    Example:

    javascript
    // Spread operator with arrays const arr1 = [1, 2, 3]; const arr2 = [...arr1, 4, 5]; console.log(arr2); // Output: [1, 2, 3, 4, 5] // Spread operator with objects const obj1 = { name: "John", age: 30 }; const obj2 = { ...obj1, city: "New York" }; console.log(obj2); // Output: { name: "John", age: 30, city: "New York" }

    These are some of the most common JavaScript interview questions that are frequently asked, along with detailed explanations and examples. Understanding these concepts will help you prepare well for your interview.

    Comments

    Popular posts from this blog

    SQL Query :- Create Tables,Primary key,Foreign key,Merge Statment

    AngularJS

    GridView Design Using CSS