Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
Share on:

Frequently Asked JavaScript Interview Questions and Answers

Frequently-Asked-JavaScript-Interview-Questions-and-Answers
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

Having JavaScript in your portfolio increases the chances of getting a software developer role. That said, let’s check out the frequently asked JavaScript interview questions.

JavaScript is one of the most used languages in web development. It’s used to develop almost any type of application now.

Before jumping into the interview questions, let’s see the advantages of learning JavaScript.

JavaScript

JavaScript is a lightweight, interpreted, or just-in-time compiled programming language. It is one of the core languages of the world wide web. You know the other two core languages of www. You better search for them if you don’t.

JavaScript is mainly created for the web. But it’s not only for the web now. With the help of environments like Node, Deno, etc.., we can run it on almost any platform.

Let’s check out some advantages of it.

Advantages of JavaScript

  1. Easy to get started with. You can learn it even without any coding knowledge.
  2. Large community around it. You will get all the help you want if you are stuck anywhere.
  3. There are a lot of libraries/frameworks build using JavaScript, which helps to develop applications faster.
  4. We can develop frontend, backend, android, iOS, etc.., applications with JavaScript. We can create almost any type of application with it. But, it’s more robust in web development.

What are the data types in JavaScript?

The data types are used to store different types of data. Data types will differ from one programming language to another. In JavaScript, we have 8 data types. Let’s see them one by one.

  • Number
  • String
  • Boolean
  • Undefined
  • Null
  • BigInt
  • Symbol
  • Object

All the data types except Object are called primitive values. And they are immutable.

What are the built-in methods in JavaScript?

The built-in methods in JavaScript are different for each data type. We can access these built-in methods using the respective data type. Let’s see some built-in methods for different data types and data structures.

  1. Number
    • toFixed
    • toString
  2. String
    • toLowerCase
    • startsWith
    • chartAt
  3. Array
    • filter
    • map
    • forEach

There are a lot of built-in methods for each data type. You can check the references for all built-in methods of different data types and data structures.

How to create an array in JavaScript?

Arrays are one of the core data structures in JavaScript. Arrays can have any type of data in them as JavaScript is dynamic. Let’s see how to create arrays in JavaScript.

We can create an array using square brackets[]. It’s straightforward and quick to create objects

// Empty array
const arr = [];

// Array with some random values
const randomArr = [1, "One", true];

console.log(arr, randomArr);

We can create an array using Array constructor. People rarely use the constructor to create arrays in general projects.

// Empty array
const arr = new Array();

// Array with some random values
const randomArr = new Array(1, "One", true);

console.log(arr, randomArr);

JavaScript arrays are mutable i.e. we can modify them as we want after creating them.

How to create an object in JavaScript?

Aside array, the object is another core data structure in JavaScript. Objects are using store the key-value pairs. The key must be an immutable value, whereas the value can be anything. Let’s see how to create objects in JavaScript.

We can create objects using curly brackets {}. It’s straightforward and quick to create objects.

// Empty object
const object = {};

// Object with some random values
const randomObject = { 1: 2, one: "Two", true: false };

console.log(object, randomObject);

We can create objects using Object constructor. People rarely use this in general projects.

// Empty object
const object = new Object();

// Object with some random values
const randomObject = new Object();
randomObject[1] = 2;
randomObject["one"] = "Two";
randomObject[true] = false;

console.log(object, randomObject);

JavaScript objects are mutable i.e., we can modify them after creating, as you see in the 2nd example.

How do you debug JavaScript code?

Debugging code is not straightforward. And it’s different from one programming language to another, one project to another, etc..; let’s see the common things used to debug JavaScript.

#1. Logging

We can use the console.log statements at multiple places in our code to identify the bug. The code will stop running the next lines of code when there is a bug in the previous line.

Logging is one of the old debugging methods, which is pretty much effective for small projects. It’s a common debugging technique for any programming language.

#2. Developer Tools

JavaScript is mostly used for developing web applications. So, almost all browsers have developer tools now that help to debug the JavaScript code.

One of the most used debugging methods is setting breakpoints in the developer tools. The breakpoints stop the execution of JavaScript and give all the info about the execution at the moment.

We can set multiple breakpoints around the place where we are getting errors and see what’s causing it. It’s the most effective way to debug JavaScript web applications.

#3. IDEs

We can use the IDEs to debug JavaScript. VS Code supports debugging with breakpoints. The debugging feature may differ based on the IDE you are using. But, most of the IDEs will have that feature.

How to add JavaScript code in an HTML file?

We can add the JavaScript HTML file using the script tag. You can check the example below.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Geekflare</title>
  </head>
  <body>
    <h1>Geekflare</h1>

    <script>
      // JavaScript code goes here
      console.log("This is JavaScript code");
    </script>
  </body>
</html>

What are cookies?

Cookies are key-value pairs used to store small information. The information can be anything. We can set the expiry time of the cookies, which will be deleted after their expiry time. These are widely used to store the users’ information.

Cookies won’t be cleared even if we refresh the page until we delete them or they expire. You can check the cookies of any web app/web page in any browser by opening the developer tools.

We can read the cookie in JavaScript using document.cookie. It will return all the cookies that we created.

console.log("All cookies", document.cookie);

It will return an empty string if there are no cookies.

We can create the cookies by setting the key-value pair to the document.cookie. Let’s see an example.

document.cookie = "one=One;";

In the above syntax, the one cookie key and One is its value. We can add more attributes to the cookie like domain, path, expires, etc..; each of them should be separated by a semicolon (;). All the attributes are optional.

Let’s see an example with attributes.

document.cookie = "one=One;expires=Jan 31 2023;path=/;";

In the above code, we have added an expiry date and path to the cookie. If the expiry date is not provided, the cookie will be deleted after the session. The default path will be the file path. The expiry date format should in GMT.

Let’s see how to create multiple cookies.

document.cookie = "one=One;expires=Jan 31 2023;path=/;";
document.cookie = "two=Two;expires=Jan 31 2023;path=/;";
document.cookie = "three=Three;expires=Jan 31 2023;path=/;";

The cookies won’t be overwritten if the key or path is different while setting multiple cookies. If the key and path are the same, then it will overwrite the previous cookie. Check out the below example, which will overwrite the previous set cookie.

document.cookie = "one=One;expires=Jan 31 2023;path=/;";
document.cookie = "one=Two;path=/;";

We have removed the expiry date from the cookie and changed the value.

Use the expiry date a future date when you are testing the code for it to work correctly. If you keep the same date Jan 31 2023 even after the Jan 31 2023, cookies won’t be created.

We have seen how to create and update cookies. Let’s see how to delete cookies.

Deleting cookies is easy. Just change the expiry date of the cookie to any past date. Check the example below.

// Creating cookies
document.cookie = "one=One;expires=Jan 31 2023;path=/;";
document.cookie = "two=Two;expires=Jan 31 2023;path=/;";
document.cookie = "three=Three;expires=Jan 31 2023;path=/;";

// Deleting the last cookie
document.cookie = "three=Three;expires=Jan 1 2023;path=/;";

You won’t find the last cookie in the cookies as it’s deleted in the last line of the code. That’s it for the min cookies tutorial.

What are the different JavaScript frameworks?

There are a lot of JavaScript frameworks out there. React, Vue, Angular, etc.., for UI development. Express, Koa, Nest, etc.., for server-side development. NextJS, Gatsby, etc.., for static site generation. React Native, Ionic, etc.., for mobile app development. We have mentioned some of the JavaScript frameworks here. You can find more frameworks that will take a lot of time to explore. Explore when you need them.

Closures in JavaScript

A closure is a function bundled with its lexical scope and its parent lexical environment. With closures, we can access the outer scope data. The closures are formed when the functions are created.

function outer() {
  const a = 1;
  function inner() {
    // We can access all the data from the outer function scope here
    // The data will be available even if we execute this function outside the outer function 
    // as inners' closure formed while creating it
    console.log("Accessing a inside inner", a);
  }
  return inner;
}

const innerFn = outer();
innerFn();

Closures are widely used in JavaScript applications. You might have used them before without realizing that they are closures. There is a lot more than this to learn about the closures. Make sure you have learned this concept completely.

Hoisting in JavaScript

Hoisting is a process in JavaScript where the declaration of variables, functions, and classes moves to the top of the scope before executing the code.

// Accessing `name` before declaring
console.log(name);

// Declaring and initializing the `name`
var name = "Geekflare";

If you run the above code, you won’t see any error. But in most languages, you will get the error. The output will be undefined as hoisting only moves the declarations to the top, and it won’t initialize it until line number 3.

Change the var to let or const as follows, and run the code again.

// Accessing `name` before declaring
console.log(name);

// Declaring and initializing the `name`
const name = "Geekflare";

Now, you will get the reference error saying we can’t access the variable before initializing it.

ReferenceError: Cannot access 'name' before initialization

So, here the let and const are introduced in ES6, which can’t be accessed before initialized, as the error suggests. This is because the variables declared with let or const will be in Temporal Dead Zone (TDZ) until the line it’s initialized. We can’t access the variables from TDZ.

Currying in JavaScript

Currying is a technique to convert functions with many parameters into fewer parameters with multiple callables. With it, we can convert a function callable add(a, b, c, d) to add(a)(b)(c)(d) callable. Let’s see an example of how to do it.

function getCurryCallback(callback) {
  return function (a) {
    return function (b) {
      return function (c) {
        return function (d) {
          return callback(a, b, c, d);
        };
      };
    };
  };
}

function add(a, b, c, d) {
  return a + b + c + d;
}

const curriedAdd = getCurryCallback(add);

// Calling the curriedAdd
console.log(curriedAdd(1)(2)(3)(4));

We can generalize the getCurryCallback the function which will be used for different functions to convert into currying callables. You can refer to JavaScript Info for more details on it.

Difference between document and window

The window is the topmost object in the browser. It contains all the info about the browser window, like history, location, navigator, etc..; it’s globally available in JavaScript. We can use it directly in our code without any imports. We can access the properties and methods of the window object without window.

The document is the part of window object. All the HTML loaded on the web page is converted to the document object. The document object refers to the special HTMLDocument element, which will have different properties and methods like all HTML elements.

The window the object represents the browser window and document represents the HTML document loaded in that browser window.

Difference between client-side and server-side

The client side refers to the end user using the application. The server side refers to the web server where the application is deployed.

In the frontend terminology, we can say browser on users’ computers as client side and cloud services as server side.

Difference between innerHTML and innerText

Both the innerHTML and innerText are the properties of HTML elements. We can change the contents of an HTML element using these properties.

We can assign the HTML string to innerHTML a property rendered like normal HTML. Check the below example.

const titleEl = document.getElementById("title");

titleEl.innerHTML = '<span style="color:orange;">Geekflare</span>';

Add one element with the id title to your HTML and add the above script to the JavaScript file. Run the code and see the output. You will Geekflare in orange color. And if you inspect the element, it will be inside the span tag. So the innerHTML will take the HTML string and render it as normal HTML.

The innerText on the other side will take a normal string and render it as it is. It won’t render any HTML like innerHTML. Change the innerHTML to innerText in the above code and check the output.

const titleEl = document.getElementById("title");

titleEl.innerText = '<span style="color:orange;">Geekflare</span>';

Now, you will see the exact string that we provided on the web page.

Difference between let and var

The let and var keywords are used to create variables in JavaScript. The let keyword is introduced in ES6.

The let is a block-scoped and var is function-scoped.

{
  let a = 2;
  console.log("Inside block", a);
}
console.log("Outside block", a);

Run the above code. You will get an error on the last line as we can’t access let a outside the block because it’s block-scoped. Now, change it to var and run it again.

{
  var a = 2;
  console.log("Inside block", a);
}
console.log("Outside block", a);

You won’t get any error as we can access the a variable outside the block as well. Now, let’s replace the block with a function.

function sample() {
  var a = 2;
  console.log("Inside function", a);
}
sample();
console.log("Outside function", a);

You will get a reference error if you run the above code as we can’t access var a it outside the function because it’s function-scoped.

We can redeclare the variables using var keyword but we can’t redeclare the variables using let keyword. Let’s see an example.

var a = "Geekflare";
var a = "Chandan";
console.log(a);
let a = "Geekflare";
let a = "Chandan";
console.log(a);

The first piece of code won’t throw any error and the value is a will be changed to the latest assigned value. The 2nd piece of code will throw an error as we can’t redeclare variables using let.

Difference between session storage and local storage

The session storage and local storage are used to store info on the users’ computers which can be accessed without the internet. We can store the key-value pairs in both session storage and local storage. Both key and value will be converted to strings if you provide any other data type or data structure.

The session storage will be cleared after the session is over (when the browser is closed). The location storage won’t be cleared until we clear it.

We can access, update, and delete session storage and location storage with sessionStorage and localStorage objects respectively.

What is NaN in JavaScript?

The NaN is abbreviated as Not-a-Number. It represents that something is not a legal/valid number in JavaScript. There are some cases where we will get NaN as output like 0/0, undefined * 2, 1 + undefined, null * undefined etc..,

What is Lexical scoping?

The lexical scope refers to accessing the variables from its parents’ scope. Let’s say we have a function with two inner functions. The innermost function can access its two parent functions’ scope variables. Similarly, the 2nd level function can access the outermost function scope. Let’s see it in an example.

function outermost() {
  let a = 1;
  console.log(a);
  function middle() {
    let b = 2;
    // `a` are accessible here
    console.log(a, b);
    function innermost() {
      let c = 3;
      // both `a` and `b` are accessible here
      console.log(a, b, c);
    }
    innermost();
  }
  middle();
}
outermost();

JavaScript uses a scope chain to find the variable when we are accessing it somewhere in the code. First, it will check the variable in the current scope, and then the parent scope until the global scope.

What is passed by value and passed by reference?

The pass by value and pass by reference are two ways to pass the arguments to a function in JavaScript.

Pass by value: it creates a copy of the original data and passes it to the function. So, when we made any changes in the function it won’t affect the original data. Check the below example.

function sample(a) {
  // changing the value of `a`
  a = 5;
  console.log("Inside function", a);
}
let a = 3;
sample(a);
console.log("Outside function", a);

You will see that the original value of the a is not changed even though we changed it inside the function.

Pass by reference: it passes the reference of the data to the function. So, when we made any changes in the function, it will also change the original data.

function sample(arr) {
  // adding a new value to the array
  arr.push(3);
  console.log("Inside function", arr);
}
let arr = [1, 2];
sample(arr);
console.log("Outside function", arr);

You will see that the original value of the arr is changed when we change it inside the function.

Note: all primitive data types are passed by value, and non-primitive are passed by reference.

What is memoization?

Memoization is a technique that stores the computed values in caches and uses them when we need them again without computing them again. It will speed up the execution of the code if the computation is very heavy. There is a storage tradeoff which is not a big issue compared to time.

const memo = {};
function add(a, b) {
  const key = `${a}-${b}`;

  // checking whether we computed the value already or not
  if (memo[key]) {
    console.log("Not computing again");
    return memo[key];
  }

  // adding the newly computed value to cache
  // here cache is a simple global object
  memo[key] = a + b;
  return memo[key];
}

console.log(add(1, 2));
console.log(add(2, 3));
console.log(add(1, 2));

It’s a simple example that demonstrates memoization. Here, adding two numbers is not a heavy computation tough. It’s just for the demo.

What is the rest parameter?

The rest parameter is used to collect all the remaining parameters in a function. Let’s say we have a function that will accept a minimum of 2 arguments and can accept any number of parameters at a maximum. As we don’t have the maximum number of arguments, we can collect the first 2 parameters with normal variables and all others with the rest parameter using the rest operator.

function sample(a, b, ...rest) {
  console.log("Rest parameter", rest);
}

sample(1, 2, 3, 4, 5);

The rest parameter will be an array of the last three arguments in the above example. With this, we can have any number of parameters for a function.

One function can have only one rest parameter. And the rest parameter should be the last one in the order of the parameters.

What is object destructuring?

Object destructuring is used to access the variables from the object and assign them to variables with the same names as object keys. Let’s see an example.

const object = { a: 1, b: 2, c: 3 };

// Object destructuring
const { a, b, c } = object;

// Now, a, b, c will be used as normal variables
console.log(a, b, c);

We can change the variables of destructured variables in the same line as follows.

const object = { a: 1, b: 2, c: 3 };

// Changing the names of `a` and `b`
const { a: changedA, b: changedB, c } = object;

// Now, changedA, changedB, c will be used as normal variables
console.log(changedA, changedB, c);

What is array destructuring?

Array destructuring is used to access the variables from the array and assign them to variables. Let’s see an example.

const array = [1, 2, 3];

// Array destructuring
// It's based on the index of the array
const [a, b, c] = array;

// Now, we can use a, b, c as normal variables
console.log(a, b, c);

What are event capturing and event bubbling?

Event capturing and event bubbling are two ways of event propagation in HTML DOM. Let’s say there are two HTML elements, one inside another. And an event occurs on the inner element. Now, the event propagation mode will decide the order of these events’ execution.

Event bubbling: it runs the event handler on the element first, then its element, and then it goes all the way up to the topmost element. This is the default behaviour of all the events.

Event capturing: we need to specify in the event that we need to use this type of event propagation. We can specify it while adding the event listener. The events will execute in the following order if we have the event capturing enabled.

  1. The events starts executing from the topmost element till the target element to down.
  2. The event on the target element will be executed again.
  3. The bubbling event propagation will again occur until the topmost element is up.

We can stop the event propagation by calling event.stopPropogation a method in the event handler.

What are the Promises in JavaScript?

The Promise the object is used for the asynchronous operations which will complete in future with a success or failure state.

A Promise can be in one of the following states.

  1. pending – when the operation is still in progress.
  2. fulfilled – when the operation is completed successfully. We will have results (if any) in the success state.
  3. rejected – when the operation is completed with a failure. We will have the reason (error) why it failed.

Let’s see two examples of success and failure cases.

// Promise which will complete successfully
const successPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve({ message: "Completed successfully" });
  }, 300);
});
successPromise
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.log(error);
  });

// Promise which will complete with failure state
const failurePromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject(new Error("Failing the promise for testing"));
  }, 300);
});
failurePromise
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.log(error);
  });

You can have more than one then chaining if required. The previously returned data will be accepted in the next then callback.

Explain the different types of scope in JavaScript

There are two types of scope in JavaScript. The global scope and local scope.

You might have heard about the function scope and block scope as well. They are local scopes for var and let, const respectively.

What are self-invoking functions?

The self-invoking functions are nameless functions that will be executed immediately after creation. Let’s see some examples.

// Without any parameters
(function sayHello() {
  console.log("Hello, World!");
})();

// With parameters
(function add(a, b) {
  console.log("Sum", a + b);
})(1, 2);

We can even pass the arguments to the self-invoking functions as you have seen in the example.

What are arrow functions?

The arrow function is syntactic sugar to the normal function with some changes. They behave like normal functions in general use cases. Arrow functions come in handy when we have to have callbacks. Let’s see its syntax.

// arrow functions will return by default if it doesn't have any brackets
let add = (a, b) => a + b;

console.log(add(1, 2));

There are some differences between the arrow functions and normal functions.

  • Arrow functions don’t have their own this binding. The this keyword inside the arrow function refers to its parent scope this.
  • Arrow functions can’t be used as constructor functions

What are callbacks?

A callback is a function that is passed to another function that is invoked inside that function. Using callbacks is a common thing in JavaScript. Let’s see an example.

function sample(a, b, callback) {
  const result = a + b;
  callback(result);
}

function finished(result) {
  console.log("Finished with", result);
}

sample(1, 2, finished);

The function finished is passed as a callback to the sample. The finished function is invoked with the result after performing some action. You will see the callbacks usage mostly in asynchronous operations like promises, setTimeout, etc..,

What are the different types of errors?

Let’s check some errors in JavaScript.

ReferenceError: this error will occur if the variable that we are accessing is available.

TypeError: JavaScript will throw this error if the error doesn’t match with other types of errors. It will also occur when we try to perform an action which is not compatible with the data.

SyntaxError: this error will occur if the JavaScript syntax is not correct.

There are some other types of errors as well. But these are the common error types in JavaScript.

What are the different scopes of variables in JavaScript?

There are two scopes of variables in JavaScript. The variables declared using the var keyword will have function scope, and the variables declared with the let and const will have the block scope.

Refer to the 17th question for more details about these variables’ scope.

What are escape characters in JavaScript?

The backslash is the escape character in JavaScript. It’s used to print some special characters which we can’t print in general. Let’s say we want to print apostrophe (') inside a string which we can’t do normally as the string will end at the second apostrophe. In that case, we will the escape character to avoid ending the string at that point.

const message = 'Hi, I\'m Geekflare';
console.log(message);

We can achieve the above output without using escape character by replacing the outside single apostrophes with double apostrophes. But it’s just an example of how to use an escape character. There are other characters for which we definitely need escape character like \n, \t, \\ etc..,

What are BOM and DOM?

Browser Object Model (BOM): all browsers have BOM representing the current browser window. It contains our topmost window object which is used to manipulate the browser window.

Document Object Model (DOM): browsers create the DOM when the HTML is loaded in the tree structure. We can manipulate the HTML elements using DOM API.

What is a screen object?

The screen object is one of the properties of the global window object. It contains different properties of the screen on which the current browser window is rendered. Some of the properties are width, height, orientation, pixelDepth, etc.

Conclusion

There are might be follow-up questions for all the above questions. So, you need to prepare the concepts around all the above questions.

You may also explore some frequently asked Java interview questions and answers.

Happy Learning 🙂

Thanks to our Sponsors
More great readings on Career
Power Your Business
Some of the tools and services to help your business grow.
  • Invicti uses the Proof-Based Scanning™ to automatically verify the identified vulnerabilities and generate actionable results within just hours.
    Try Invicti
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.
    Try Brightdata
  • Semrush is an all-in-one digital marketing solution with more than 50 tools in SEO, social media, and content marketing.
    Try Semrush
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.
    Try Intruder