DEV Community

Pratik Singh
Pratik Singh

Posted on

Essential JavaScript Interview Questions You Should Know

As someone who's navigated through numerous JavaScript interviews, I’ve compiled a list of essential questions that tested my skills and understanding of core concepts. In this first part of the series, I’m sharing 40 questions I personally faced, covering everything from fundamentals to key interview topics.

These questions are not just theoretical; they challenge you to demonstrate your practical knowledge and problem-solving abilities. Whether you’re preparing for a front-end or full-stack role, these questions will help you sharpen your skills.

Chalo Shuru karte hai!

1. Is javaScipt dynamic type or variable type language?

Answer: JavaScript is a dynamically typed language, meaning variable types can change at runtime instead of being set at compile time.

2. How do you send http requests to backend?

Answer: Fetch API, Axios, XMLHttpRequest

3. What is Execution Context?

Answer: In JavaScript, the Execution Context is the environment where code runs and decides what variables, objects, and functions are available to use. Each time a function runs, a new execution context is made just for that function, holding its own variables and scope.

Each execution context has two main phases:

  1. Memory Creation Phase: JavaScript first scans the code and allocates memory for variables and functions.
  2. Execution Phase: The code runs line-by-line.

4. What is Lexical Environment?

Answer: A lexical environment in JavaScript is a data structure that stores variables and functions defined in the current scope, along with references to all outer scopes. It is also known as the lexical scope.

5. What's the difference between null and undefined?

Answer: null: An assignment value that means a variable points to no object, showing that it has no specific value.

undefined: Means a variable is declared but has no assigned value, showing the variable itself is missing a value.

Type of null is object.
Type of undefined is undefined.

6. How JavaScript handle memory?

Answer: JavaScript manages memory primarily through automatic garbage collection, meaning it automatically allocates and releases memory during code execution.

7. Explain Event Loop?

Answer: JavaScript is a single-threaded language, meaning it can only execute one task at a time within a single call stack. However, despite this single-threaded nature, JavaScript is capable of performing asynchronous, non-blocking operations thanks to the event loop.

The event loop is a fundamental mechanism in JavaScript that handles asynchronous operations. When a task, such as an HTTP request or a DOM event, is initiated, it is handed off to browser APIs.

The event loop continuously monitors the call stack and the task
queues. If the call stack is empty, the event loop first checks the
microtask queue for any pending tasks and executes them.

Once the microtask queue is empty, the event loop then checks the macrotask queue and moves tasks from there to the call stack for execution. This process ensures that high-priority tasks (microtasks) are executed before lower-priority tasks (macrotasks).

8. Hoisting and Temporal Dead Zone?

Answer: Hoisting is a JavaScript feature that allows you to use variables and functions before they are declared. This means that you can variables and functions before they are defined in your code. Hoisting is done by the JavaScript engine, which moves the declaration of variables and functions to the top of their "scope".

In JavaScript, before executing any code, the JavaScript engine performs a memory preparation phase known as hoisting. During this phase, the engine allocates memory for variables and functions.

Function declarations are fully hoisted, meaning they can be invoked anywhere within their scope, even before their actual line of declaration.

Variables declared with var are hoisted and initialized with undefined. This means you can access var variables before their declaration, but their value will be undefined.

On the other hand: Variables declared with let and const are also hoisted but remain uninitialized. Accessing them before their declaration in the code results in a ReferenceError.

Temporal Dead Zone:

This period between the start of the block and the actual declaration of a let or const variable is called the Temporal Dead Zone (TDZ). The TDZ exists from the start of the block until the line where the variable is declared and initialized.

Temporal dead zone is a concept in JS related to let and const declarations. Variables with let or const declarations are hoisted to the top of their scope, but they are not immediately available in the code. This means that you can use a variable before it is declared, but the value of the variable will be undefined until it is assigned a value.

9. Scope and Scope Chain?

Answer: Scope governs the accessibility of variables in different parts of the code. It determines where a variable can be accessed and
where it cannot.

There are three types of scopes:

Global Scope: Variables declared in the global scope can be
accessed from anywhere in the code.
Local Scope: Variables declared within a function are only
accessible within that function.
Block Scope: Variables declared inside a block (like within curly
braces {}) are only accessible within that block.

Scope Chain:

Scope chain means a chain of references. JavaScript doesn't give up; it has a hunting mechanism for variables. It keeps searching for the variable. First, it will check in the local scope to see if the variable is accessible. If not, it will look in the outer scope. It will keep going until it reaches the global scope or the global execution context. This continuous hunting for a variable during the chain is called scope chaining. The execution context always searches from the inner scope to the outer scope, but it can't go from the outer scope to the inner scope.

10. Prototypal Inheritance?

Answer: Linking of prototypes of a parent object to a child object to share and utilize properties of parent class. It means that properties and methods can be transferred from one object to another through the prototype.

For example, methods like .join and .length are part of prototypal inheritance because these properties come from the main Object class in JavaScript and are available in your objects.

In JavaScript, everything is an object, so objects can share properties. This means that arrays can use methods from objects, and strings can do the same.

let faang = {
    name: "google",
    salary: function(){
        console.log("100K Salary")
    }
}
Enter fullscreen mode Exit fullscreen mode
let engineer = {
    employeeId: 1278,
    role: function(){
        console.log("Frontend Developer")
    }
}
Enter fullscreen mode Exit fullscreen mode

Older Way:

engineer.__proto__ = faang;
Enter fullscreen mode Exit fullscreen mode

New Way:

let engineer = Object.create(faang, {
    role: function(){
        console.log("Backend Developer")
    }
})

Object.setPrototypeOf(engineer, faang);

// let res = Object.getPrototypeOf(faang);

Enter fullscreen mode Exit fullscreen mode

11. Explain Promises in JavaScript?

Answer: Promises are a way to handle asynchronous operations in JavaScript. They allow you to write code that can be executed asynchronously, without blocking the main thread. Promises are created using the Promise constructor, and can be chained together using the then method.

A Promise in JavaScript acts as a placeholder that can resolve or reject in future.

Promises have three states: pending, fulfilled, and rejected. When a promise is pending, it means that the asynchronous operation is still in progress. When a promise is fulfilled, it means that the asynchronous operation has completed successfully. When a promise is rejected, it means that the asynchronous operation has failed.

Handling Promises

Promises provide methods to handle the outcome of the asynchronous operation:

.then(): Used to handle the fulfilled state and obtain the resolved
value.
.catch(): Used to handle the rejected state and catch any errors
that occurred during the execution.
.finally(): This method executes a callback when the promise is
settled, meaning it will run whether the promise is fulfilled or
rejected.

12. Explain Async Await?

Answer: Async/await is a syntax feature in JavaScript that allows you to write asynchronous code in a more synchronous way. It uses the async and await keywords to define asynchronous functions

In JavaScript async function returns a Promise. The await keyword pauses the execution of the async function until the awaited promise resolves. After await rest of async function gets in microtask queue. This allows for more readable and manageable asynchronous code.

async function fetchData() {
  try {
    const response = await fetch('https://api.freeapi.app/v1/jokes/random');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

fetchData()
  .then(() => console.log('Data fetched'))
  .catch(error => console.error(error));
Enter fullscreen mode Exit fullscreen mode

13. Explain this keyword?

Answer: The “this” keyword refers to the object that is currently executing the function. Its value depends on the context in which the function is called. In the global context (such as in a browser), this refers to the window object

14. Explain Closure and Lexical Scope?

Answer: Closures are functions that have access to variables from their outer scope, even after the outer function has finished executing.

Here's an example of a closure in JavaScript:

function outerFunction() {
  const outerVariable = 'I am an outer variable';

  function innerFunction() {
    console.log(outerVariable); // Output: I am an outer variable
  }

  return innerFunction;
}

const closure = outerFunction();
closure(); // Output: I am an outer variable
Enter fullscreen mode Exit fullscreen mode

In this example, the outerFunction function defines a variable outerVariable and a function innerFunction that has access to outerVariable. The innerFunction returns the outerFunction function, which allows it to be called later.

One DOM related example of a closure is the addEventListener method. The addEventListener method allows you to attach event listeners to elements in the DOM. The event listener function has access to the element's properties and methods, even after the element has been removed from the DOM.

Here's an example of using the addEventListener method with a closure:

const button = document.getElementById('myButton');

function handleClick() {
  console.log('Button clicked');
}

button.addEventListener('click', handleClick);
Enter fullscreen mode Exit fullscreen mode

In this example, the handleClick function is defined inside the addEventListener method. The handleClick function has access to the button element, even after the button element has been removed from the DOM.

Lexical Scope:

In JavaScript, lexical scope is the concept of determining the scope of a variable based on its declaration. This means that the scope of a variable is determined by the block of code in
which it is declared, not by the block of code in which it is used.

15. Is javascript single threaded or multi-threaded?

Answer: JavaScript is a single-threaded language, meaning it has one call stack and one memory heap. It executes code in order, completing one piece of code before moving on to the next. This structure allows JavaScript to handle asynchronous operations without blocking the main thread.

Asynchronous behavior lets us use features like setTimeout, AJAX, and promises. These functions are managed by the browser, not JavaScript itself, which helps keep the main thread free to run other code while waiting for these operations to complete.

16. Explain how javascript engines works?

Answer: JavaScript engines are programs that execute JavaScript code. They are found in web browsers and other environments that host JavaScript. The most popular JavaScript engines are Google's V8, SpiderMonkey, and JavaScriptCore. These engines are written in C++ and are used to execute JavaScript code.

17. Difference between var, let and const?

Answer:

-var: The scope of a variable defined with the keyword “var” is limited to the “function” within which it is defined. If it is defined outside a function, the scope of the variable is global. Default value of var is undefined.

  • let: The scope of a variable defined with the keyword “let” or “const” is limited to the “block” defined by curly braces i.e. {}. Default value of let is uninitialized.
  • const: The scope of a variable defined with the keyword “const” is limited to the block defined by curly braces. However if a variable is defined with keyword const, it cannot be reassigned. Default value of const is uninitialized.

18. Different types of data types in javascript?

Answer: There are mainly two types of data types in JavaScript: primitive data types and object (reference) data types.

Primitive data types are the basic data types in JavaScript. They include numbers, strings, booleans, null, and undefined. Symbols are also primitive data types, that represent unique identifiers.

Object data types are data types that contain other data types. They are created using object literals or constructor functions. Objects, Arrays, and Functions are examples of object data types.

19. Discuss callback?

Answer: Callback functions are functions that are passed as arguments to other functions and are called when a certain event occurs. They are commonly used in JavaScript to handle asynchronous operations, such as making HTTP requests or reading from a file.

20. Discuss Callback Hell?

Answer: Callback hell is a problem in JavaScript where functions are nested inside each other, making the code difficult to read and understand. It can lead to callbacks being called multiple times or not being called at all, which can cause unexpected behavior.

Here's an example of callback hell:

fetchRandomJoke(joke) =>{
  console.log(joke);
  translateJoke(joke, translation) =>{
    console.log(translation);
    writeToFile(translation, file) =>{
      console.log('Joke written to file');
      sendEmail(translation, email) =>{
        console.log('Joke sent to email');
      }
    }
  }
}

//better way to do it
const fetchRandomJoke = async (joke) => {
  const joke = await fetchJoke();
  const translation = await translateJoke(joke);
  await writeToFile(translation, file);
  await sendEmail(translation, email);
}
Enter fullscreen mode Exit fullscreen mode

21. How to create object in javascript?

Answer: Objects are a fundamental data type in JavaScript. They can be created using object literals or constructor functions.

Object literals are enclosed in curly braces {} and are used to create objects with key-value pairs. Here's an example of an object literal:

const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};
Enter fullscreen mode Exit fullscreen mode

Constructor functions are used to create objects with custom properties and method:

function Person(name, age, city) {
  this.name = name;
  this.age = age;
  this.city = city;
}

const person = new Person('John', 30, 'New York');
Enter fullscreen mode Exit fullscreen mode

Although there are other ways to create objects such as using the Object.create() method, object literals and constructor functions are the most common ways to create objects in JavaScript.

22. How to clone a object in JavaScript?

Answer:

  1. Using Object.assign():
const original = { a: 1, b: 2 };
const clone = Object.assign({}, original);
Enter fullscreen mode Exit fullscreen mode
  1. Using the Spread Operator:
const original = { a: 1, b: 2 };
const clone = { ...original };
Enter fullscreen mode Exit fullscreen mode

23. What are rest and spread operator in javascript?

Answer: Rest and spread operator are two important features in JavaScript that allow you to work with arrays and objects in a more concise and readable way.

The rest operator allows you to take an array or an object as an argument and use it in a function call.

The spread operator allows you to expand an array or an object into individual elements.

function sum(...numbers) {
  return numbers.reduce((total, number) => total + number, 0);
}

console.log(sum(1, 2, 3, 4, 5)); // Output: 15

//spread operator
const arr1 = [1, 2, 3];
const arr2 = [4, 5];

const arr3 = [...arr1, ...arr2];
console.log(arr3); // Output: [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

In this example, the sum function takes an array of numbers as an argument using the rest operator.
The spread operator is used to expand the array into individual elements, which are then passed to the reduce function.

24. What is higher order function in javascript?

Answer: Higher order functions are functions that take other functions as arguments or return functions as results. They are a powerful tool in JavaScript that allow you to write more flexible and reusable code.

function applyTwice(func, arg) {
  return func(func(arg));
}

console.log(applyTwice(Math.sqrt, 16))

// A higher-order function that takes a number and returns another function
function add(n) {
  return function(x) {
    return x + n; // Adds n to x
  };
}

// Using the higher-order function
const addFive = add(5); // Creates a function that adds 5
console.log(addFive(10)); // Outputs: 15
console.log(addFive(20)); // Outputs: 25
Enter fullscreen mode Exit fullscreen mode

25. Name some features of ES6 in javascript.

Answer: Here are some of the key features of ES6:

  • Arrow functions: Arrow functions provide a more concise syntax for writing functions. They are defined using the => operator.
  • Template literals: Template literals allow you to embed expressions inside strings. They are enclosed in backticks (`) and can be used to create multi-line strings.
  • Destructuring assignment: Destructuring assignment allows you to extract values from arrays or objects and assign them to variables. It is done using the = operator.
  • Spread operator: The spread operator allows you to expand an array or an object into individual elements. It is used to pass multiple arguments to a function.
  • Classes: Classes provide a way to define objects with properties and methods. They are defined using the class keyword.
  • Modules: Modules allow you to split your code into separate files and import/export functionality between them. They are defined using the import and export keywords.
  • Promises: Promises provide a way to handle asynchronous operations in JavaScript. They are used to represent the eventual completion or failure of an asynchronous operation.
  • Generators: Generators allow you to define functions that can be paused and resumed. They are defined using the function keyword.
  • Maps and Sets: Maps and Sets are data structures that allow you to store key-value pairs. They are defined using the Map and Set constructors.

Why These Questions Matter

These questions reflect the core concepts I encountered during my interviews. They’re designed to test your understanding of JavaScript in real-world scenarios.

Preparing for a JavaScript interview? Revisit these questions and practice your answers. For a more in-depth learning experience, check out my courses on quicknxt.com to gain hands-on knowledge and improve your coding skills. Let’s continue learning together!

Top comments (0)