Advanced Javascript Interview Questions And Answers

11 min read Jun 18, 2024
Advanced Javascript Interview Questions And Answers

Advanced JavaScript Interview Questions and Answers

This article will cover some advanced JavaScript interview questions and answers that are commonly asked in technical interviews.

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

Answer:

  • null represents the intentional absence of a value. It is used to indicate that a variable does not contain any data.
  • undefined represents a variable that has been declared but not yet assigned a value.

Example:

let name = null; // Intentional absence of a name
let age; // Declared but not assigned, therefore undefined 

2. What is hoisting in JavaScript, and how does it work?

Answer:

Hoisting is a JavaScript mechanism where declarations of variables and functions are moved to the top of their scope before code execution.

For variables:

  • var declarations are hoisted, but their initial value remains undefined.
  • let and const declarations are also hoisted, but they are not initialized, leading to a ReferenceError if accessed before declaration.

For functions:

  • Function declarations are hoisted entirely, including their definition.
  • Function expressions are not hoisted.

Example:

console.log(myVar); // Output: undefined
var myVar = 'Hello';

sayHello(); // Output: "Hello from function!"
function sayHello() {
  console.log("Hello from function!");
}

console.log(myLet); // Output: ReferenceError
let myLet = 'World'; 

3. Explain the concept of closures in JavaScript.

Answer:

A closure is the ability of a function to access and manipulate variables from its lexical scope, even after the outer function has finished executing. It allows inner functions to "remember" and use variables from their enclosing functions.

Example:

function outerFunction() {
  let outerVar = "Outer variable";

  function innerFunction() {
    console.log(outerVar); // Accessing outerVar from innerFunction
  }

  return innerFunction;
}

let myClosure = outerFunction();
myClosure(); // Output: "Outer variable" 

4. What are the differences between call, apply, and bind in JavaScript?

Answer:

These methods allow you to change the context (this) of a function at runtime:

  • call: Accepts arguments individually.
  • apply: Accepts an array of arguments.
  • bind: Creates a new function with a bound context and returns it. It doesn't execute the function immediately.

Example:

function greet(greeting, name) {
  console.log(`${greeting}, ${name}!`);
}

const person = { name: 'John' };

greet.call(person, 'Hello', 'John'); // Output: "Hello, John!" 
greet.apply(person, ['Hello', 'John']); // Output: "Hello, John!" 
const boundGreet = greet.bind(person, 'Hi');
boundGreet('John'); // Output: "Hi, John!" 

5. Explain the concept of event loop in JavaScript.

Answer:

The event loop is a fundamental mechanism in JavaScript that manages how asynchronous operations are handled.

It continuously checks the call stack and the callback queue:

  • Call stack: Holds the currently executing code.
  • Callback queue: Holds callbacks from asynchronous operations (e.g., timers, network requests, event listeners).

How it works:

  1. The event loop starts with an empty call stack.
  2. When an asynchronous operation completes, its callback is added to the callback queue.
  3. The event loop checks if the call stack is empty. If yes, it takes the first callback from the queue and pushes it onto the call stack.
  4. The code in the callback is executed, and the call stack is emptied again.
  5. The event loop repeats steps 3 and 4 until there are no more callbacks in the queue.

6. What are Promises in JavaScript? Explain how they work.

Answer:

Promises are objects that represent the eventual result of an asynchronous operation. They are used to handle asynchronous operations in a more structured and readable way than callbacks.

Three states:

  • Pending: The initial state, the operation is still in progress.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

Methods:

  • then: Used to handle successful results (fulfilled state).
  • catch: Used to handle errors (rejected state).
  • finally: Used to execute code regardless of the state (fulfilled or rejected).

Example:

function fetchUserData(userId) {
  return new Promise((resolve, reject) => {
    // Simulate fetching data from an API
    setTimeout(() => {
      if (userId === 'valid') {
        resolve({ name: 'John Doe', age: 30 });
      } else {
        reject(new Error('Invalid user ID'));
      }
    }, 2000);
  });
}

fetchUserData('valid')
  .then(user => {
    console.log(`User data: ${user.name}, ${user.age}`);
  })
  .catch(error => {
    console.error(error.message);
  }); 

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

Answer:

  • == (loose equality): Performs type coercion before comparison. It checks if two values are equal after converting them to the same type.
  • === (strict equality): Does not perform type coercion. It checks if two values are equal without changing their types.

Example:

console.log(1 == '1'); // Output: true (type coercion)
console.log(1 === '1'); // Output: false (no type coercion)

8. Explain the concept of prototype inheritance in JavaScript.

Answer:

Prototype inheritance is a way of creating new objects that inherit properties and methods from existing objects. Every object in JavaScript has a hidden __proto__ property that points to its prototype.

When you access a property on an object, JavaScript first checks if the property exists directly on the object. If not, it checks the prototype chain.

Example:

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

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

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

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

let myDog = new Dog('Buddy', 'Golden Retriever');
myDog.speak(); // Output: "Generic animal sound" (inherited from Animal)
console.log(myDog.name); // Output: "Buddy" (from Dog constructor)

9. How does the this keyword work in JavaScript?

Answer:

The this keyword refers to the object that is currently executing the code. Its value is determined by how the function is called.

Different ways to set this:

  • Default binding: In a regular function call, this refers to the global object (window in a browser).
  • Explicit binding: Using call, apply, or bind, you can explicitly set the value of this.
  • Implicit binding: If a function is called as a method of an object, this refers to that object.
  • New binding: When you create a new object using the new keyword, this refers to the newly created object.

10. What is the difference between a function declaration and a function expression?

Answer:

  • Function declaration: Can be used before they are defined in the code (hoisting). They are declared using the function keyword followed by the function name, parameters, and function body.
  • Function expression: Are not hoisted. They are created by assigning a function to a variable.

Example:

// Function declaration
function greet() {
  console.log("Hello!");
}

greet(); // Output: "Hello!"

// Function expression
const greet2 = function() {
  console.log("Hi!");
};

greet2(); // Output: "Hi!"

These are just a few examples of advanced JavaScript interview questions. The specific questions you encounter will depend on the role you're applying for and the company's technical requirements. However, understanding these concepts and being able to explain them clearly is a great starting point for a successful interview.

Latest Posts