DEV Community

Manoj Kumar
Manoj Kumar

Posted on

Most Asked JavaScript Interview Questions & Answers

Image description
1. What is JavaScript, and how does it differ from Java?
JavaScript is a lightweight, interpreted programming language primarily used for web development. Unlike Java, which is a full-fledged, object-oriented programming language, JavaScript is a scripting language embedded within HTML pages to enhance interactivity.

2. Explain the concept of closures in JavaScript.
Closures occur when a function retains access to variables from its outer scope, even after the outer function has finished executing. This allows for the creation of private variables and encapsulation of functionality.

function outerFunction() {
  let outerVariable = 10;

  function innerFunction() {
    console.log(outerVariable);
  }

  return innerFunction;
}

const closureExample = outerFunction();
closureExample(); // Outputs: 10
Enter fullscreen mode Exit fullscreen mode

3. What is the event loop in JavaScript?
The event loop manages the execution of code, handling events and executing callbacks. It consists of a message queue, an event loop, and a callback or “message handler.”

4. Describe the differences between let, const, and var.
var is function-scoped and hoisted.
let and const are block-scoped, and const does not allow reassignment.

function example() {
  if (true) {
    var x = 5; // Function-scoped
    let y = 10; // Block-scoped
    const z = 15; // Block-scoped and cannot be reassigned
  }

  console.log(x); // Outputs: 5
  console.log(y); // Error: y is not defined
  console.log(z); // Error: z is not defined
}
Enter fullscreen mode Exit fullscreen mode

5. How does prototypal inheritance work in JavaScript?
JavaScript uses prototypal inheritance, where objects can inherit properties and methods from other objects. Each object has a prototype chain, and if a property or method is not found in the object, JavaScript looks up the chain until it finds it.

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

Animal.prototype.sound = function () {
  console.log("Some generic sound");
};

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

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

Dog.prototype.sound = function () {
  console.log("Bark!");
};

const myDog = new Dog("Buddy", "Labrador");
myDog.sound(); // Outputs: Bark!```




Enter fullscreen mode Exit fullscreen mode

20 Most Asked JavaScript Interview Questions & Answers

Top comments (0)