JavaScript Interview Questions and Answers for 2023 (Part 2)

This article is the continuation of Part 1 read here

  1. What is a callback function in JavaScript?

In JavaScript, a callback function is a function that is passed as an argument to another function and is intended to be executed later or when a certain event occurs. The purpose of a callback function is to allow asynchronous or non-blocking operations, where the execution of code does not wait for the completion of a task.

function outer(callbackFn){
    //...
}

outer(function inner(){
    console.log("I am a callback function")
});

In the above code snippet, inner() function is known as callback function.

  1. What is a module in JavaScript and how do you create one?

Modules provide a way to encapsulate code, organize functionality, and enable reusability across multiple files in a JavaScript application.

or

In JavaScript, one script is one module. A module is nothing but a JavaScript file.

Here's an overview of how to use import and export in ES6 modules:

  • export: Using the export keyword, we make the module features available to other modules. We will be able to export functions, variables, objects, classes, etc., from a module.

  • import: As the name suggests, the import keyword is used to import other modules' features.

Default Export

You can export a default value from a module using the export default syntax. There can only be one default export per module.

// export.js
export default function add(a, b) {
  return a + b;
}

OR

// export.js
function add(a, b) {
  return a + b;
}

export default add;

Default Import

You can import the default export from a module using the import keyword followed by a variable name of your choice.

// import.js
import add from './export.js';

console.log(add(5, 3)); // Output: 8

Named Export

You can export named values or functions from a module using the export keyword followed by the name of the value/function.

// export.js
export function multiply(a, b) {
  return a * b;
}

export const PI = 3.14159
// export.js
 function multiply(a, b) {
  return a * b;
}

 const PI = 3.14159;

export {multiply, PI};

Named Import

You can import named exports from a module using the import keyword followed by braces {} and the names of the exports you want to import.

// import.js
import { multiply, PI } from './export.js';

console.log(multiply(2, 4)); // Output: 8
console.log(PI); // Output: 3.14159
  1. What is a higher-order function in JavaScript?

A higher-order function is a function that takes one or more functions as parameters and/or returns a function. Higher-order functions are often used to create more abstract and reusable pieces of code that can be used in different contexts.

Examples of higher-order functions include map(), filter(), and reduce().

  1. What is the difference between "call", "apply" and "bind" in JavaScript?

Read this article link

  1. What is event bubbling and event capturing in JavaScript?

Read this article link

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

In JavaScript, null and undefined are two distinct values that represent the absence of a value.

The main difference between the two is that null is an assignment value, while undefined indicates that a variable has not been assigned a value. Additionally, null can be explicitly used to indicate the absence of a value, while undefined cannot.

  1. What is the difference between synchronous and asynchronous code in JavaScript?

Synchronous code is executed in the order that it appears in the source code, while asynchronous code is executed at a later time or on a different thread.

Asynchronous code can be used to improve performance by allowing certain tasks to happen concurrently and without blocking the execution of other code.

  1. What is the difference between a Promise and a Callback in JavaScript?

Promises and callbacks are both mechanisms in JavaScript for handling asynchronous operations

Callbacks:

  • Callbacks are functions that are passed as arguments to another function and are called to handle the result of an asynchronous operation.

  • Callbacks have been widely used in JavaScript for asynchronous programming before Promises were introduced.

  • Callbacks allow for the execution of code when an asynchronous operation completes or an event occurs.

  • Callbacks can result in callback hell or the pyramid of doom, where multiple nested callbacks make the code harder to read and maintain.

Example with a callback:

function fetchData(callback) {
  // Simulating an asynchronous operation
  setTimeout(function() {
    const data = "Some data";
    callback(null, data); // Invoke the callback with the result
  }, 2000);
}

fetchData(function(error, result) {
  if (error) {
    console.error("Error:", error);
  } else {
    console.log("Data:", result);
  }
});

Promises:

  • Promises are objects that represent the eventual completion or failure of an asynchronous operation and allow you to handle the result using methods such as then() and catch().

  • Promises provide a cleaner and more structured way to handle asynchronous code compared to callbacks.

  • Promises support chaining and allow you to perform sequential or parallel asynchronous operations.

  • Promises can handle both success and error cases in a more unified and consistent manner.

Example with a Promise:

function fetchData() {
  return new Promise(function(resolve, reject) {
    // Simulating an asynchronous operation
    setTimeout(function() {
      const data = "Some data";
      resolve(data); // Resolve the promise with the result
      // reject(new Error("Some error")); // Reject the promise with an error
    }, 2000);
  });
}

fetchData()
  .then(function(result) {
    console.log("Data:", result);
  })
  .catch(function(error) {
    console.error("Error:", error);
  });

In this example, the fetchData function returns a Promise. The asynchronous operation is simulated with a timeout. The resolve function is used to fulfill the promise with the result, while the reject function is used to reject the promise with an error.

By using then() and catch() methods on the Promise, you can handle the success and error cases respectively.

  1. What is the difference between "document" and "window" in JavaScript?

"window" represents the browser window or tab and provides access to various browser-related properties and methods, while "document" represents the DOM of the currently loaded web page and allows for manipulation and interaction with the page's elements and content.

  1. What is the purpose of the "use strict" directive in JavaScript?

The "use strict" directive is used to enforce stricter parsing and error handling in JavaScript. This helps to avoid errors that can occur due to syntax issues, as well as improve overall code quality. Additionally, this directive also enables certain language features that are not available in regular JavaScript.

  1. Define the scopes of a variable in JavaScript?

The area of your program where a variable is defined is its scope. There will only be two scopes for a JavaScript variable.

Global Variables: A global variable is visible throughout your JavaScript code since it has a global scope.

Local Variables: Local variables are only accessible within the function in which they are defined. The parameters of a function are always specific to that function.

  1. Define undeclared and undefined variables?

Undeclared variables are not declared and don't exist in a program. A runtime error occurs if the software tries to read the value of an undefined variable.

Variables declared in the program but do not have a value are considered undefined variables. An undefined value is returned if the software tries to read the value of an undefined variable.

  1. Define ways to empty an array in Javascript.

Some of the ways by which we can empty an array in Javascript are:

  • By giving the length of the array as 0:
var x = [1, 2, 3, 4];
x.length = 0;
  • By declaring an empty array:
var x = [1, 2, 3, 4];
x = [];
  • By popping the elements of the array:
var x = [1, 2, 3, 4];
while (x.length > 0) {
  x.pop();
}
  • By using the splice array function:
var x = [1, 2, 3, 4];
x.splice(0, x.length);