110 Javascript Interview Questions 2023 (with Answers)

article_img
This Article is Part of the Guide: How to Hire a Software Developer: The Ultimate Guide guide-cat-arrow
article_img

JavaScript (JS) — is the most frequently used programming language among developers in 2021. Created for development, improvement, and change of web and mobile applications. Many famous web applications and social media platforms such as Facebook, Google, Mozilla, etc are using JavaScript.

The position of a JavaScript developer requires a specific level of education and experience. And that’s why well-crafted interview can help in hiring the best JavaScript programmer for the job.

The questionnaire must be divided into sections that judge different aspects of the job requirement, for instance, management, coding ability, etc. The JavaScript tech interview questions must also assess the motivation behind the person applying for the JavaScript developer position.

It is not necessary that the candidate would have the perfect academic standings. If the applicant’s experience and understanding of the JavaScript programming language are good, he might be a better suitor for the job as compared to someone with straight A’s but zero experience. So if the JavaScript interview questions are prepared well, they might be a better gauge of the applicant’s abilities. That is exactly what this article was created for.

Common JavaScript Interview Questions or Junior JavaScript developer Interview Questions

Here are the most basic JavaScript interview questions and their expected answers:

1. What do you know about JavaScript?

Basically, JavaScript is an object-oriented programming language that brings web pages and applications to life. Fundamentally, web browsers are the main users of JavaScript as they use it to generate an interactive and attractive interface for the users. In JavaScript, the programs that execute an assignment are known as scripts. The intriguing thing about JavaScript is that it allows the scripts to be written in the HTML of a web page and when the page loads, the scripts run automatically. Like other programming languages, JavaScript also has variables and functions.

2. What is your motivation behind applying to this role?

“I have a technical background in web development focused mainly on JavaScript. I am familiar with JavaScript ES6 and later versions as well. I enjoy taking on challenges, and JavaScript often provides such scenarios that are hard to tackle, and resolving these issues is what keeps me motivated to continue.”

3. What is the difference between JavaScript and Java?

4. What can you tell me about the history of JavaScript?

In September 1995, a Netscape programmer, Mr. Brendan Eich, created this revolutionary scripting language. The language was first named Mocha. Then due to its properties, Live Script seemed more appropriate. Later on, due to the popularity of Java, Live Script was renamed as JavaScript.

5. According to you, what are some of the distinct features of JavaScript?

This is one of the most entry-level JavaScript interview questions. Here is how it can be efficiently answered:

  • HTML and CSS are fully integrated with JavaScript.
  • JavaScript is simple to use and understand.
  • JavaScript is pre-enabled in all major web browsers.

6. About JavaScript, what would you say are its key advantages?

  • It is a very interactive language.
  • Visitors are given immediate feedback.
  • JavaScript creates very attractive interfaces.
  • Interaction with the server is minimal in JavaScript.

7. About JavaScript, what would you say are its key disadvantages?

  • Multiprocessing is not possible in JavaScript.
  • Networking applications are not supported in JavaScript.
  • Multi-threading is not an option in JavaScript.
  • Files cannot be written or read in JavaScript.

8. What is NEGATIVE_INFINITY?

In the JavaScript programming language, negative infinity refers to a constant that is the smallest of all numbers. This means that no other number is smaller than this constant. Usually, when a negative number is divided by zero, the answer is returned as negative infinity.

9. Can you differentiate view state and session state?

The session state is user-specific, and changes made here are visible across all pages in the web application. On the other hand, the view state is page-specific in a session, and the changes made here cannot be seen on other pages.

10. What are the types of pop-up boxes in JavaScript?

There are three pop-up boxes in JavaScript, namely:

  • Alert box: Used to confirm any information submission from the user.
  • Prompt box: Used to get the user to input a value or a passcode before getting to a page.
  • Confirm box: Used to get something verified from the user.

11. How is the client machine’s operating system detected in JavaScript?

The operating system on a client machine can be detected by using the navigator.userAgent or the navigator.appVersion property. It should be noted that the navigator App version is a read-only property. The user agent returns complete information about the client machine, while the App version only returns a string with the operating system’s name on the client machine.

12. Why are comments used, and how can you make a comment in JavaScript?

Usually, developers write comments to aid the reader in understanding their code. Also, to stop unnecessary code from running along the necessary code. There are two ways a comment can be made in JavaScript. If it is a single-line comment, two forward slashes will do the job (//). In the case of a multi-line comment, a forward slash is added with an asterisk, and the comment is written. The comment is then closed by a forward slash. /* your code here  */  

13. What is the role of bind in JavaScript?

Bind() is a method that is used to tie an object to a function. This means that when called, the function will return that object. Basically, a new function is created that allows passing the desired number of arguments in this array.

14. Explain the NaN in JavaScript

As in other applications and programming languages, NaN is abbreviated for Not a Number in JavaScript as well. In JavaScript, whenever a function is supposed to return a number but due to some error it cannot, the answer is NaN, which indicates an error in the computation process. Sometimes during data conversion (e.g. value to number), if the process is not completed, the developer sees a NaN.

15. What do you know about the JavaScript ES6 version?

Since the creation of JavaScript, it has been encountering several challenges, which have been revised in different updated versions over time. The ES6, also known as the ECMAScript 6 or the ECMAScript 2015, is considered to be the 2nd major update to JavaScript. There was a big addition to the features of JavaScript in the ES6. Newly added features in the ES6 were:

  • The let and const keywords
  • Arrow Functions
  • For/of
  • Map and Set Objects
  • Classes
  • Promises
  • Symbol
  • Default and Function Rest Parameters
  • String includes()
  • String startsWith()
  • String endsWith()
  • Array from()
  • Array keys()
  • Array find()
  • Array findIndex()
  • New Math, Number, and Global Methods
  • New Number Properties
  • Object entries
  • JavaScript Modules

JavaScript Fundamental Interview Questions

16. Have you heard of a “named function”? If yes, how would you define it?

Yes, it is a very common terminology in the JavaScript programming language. A named function is basically a function that has been assigned a specific name that can be used as its callback. A function with such an identifier is called a named function. The name should have a meaning so that it provides some context about the nature of the function that it refers to. Generic, too-long, or too-short names must be avoided, it is better to attach some additional information with a name in the form of a prefix or suffix.

17. In JavaScript, what is a function, and what are the types of functions?

A function is a collection of statements that take inputs, perform some specific computation, and return output.

There are two types of functions in JavaScript, Named functions and Anonymous functions.

18. Can you state the definition of an anonymous function?

As the name suggests, an anonymous function is a function that has no name assigned to it. These functions are created with the function operator as it is more flexible. An anonymous function can be used instead of an expression. Also, an anonymous function can be assigned to a variable.

19. Keeping the concepts of JavaScript in mind, how would you describe closure?

Closure refers to the fusion of the lexical environment in which a function is declared with the function itself. One can say that closure itself is an inner function with access to the outer variables as well as the variables of the enclosing function. There are 3 scope chains of a closure:

  • Global variables.
  • Own variables.
  • Outer function variables.

20. What is the arguments object in JavaScript?

In JavaScript, inside a function, the arguments object has the values of arguments passed to that function. Using the arguments object, we can point to all of the functions passed to a function. The arguments object has properties similar to an array, so we can pick individual values by using the array indexing notation.

21. How can you differentiate between JavaScript and JScript?

22. What are the different types of data types in JavaScript?

  • Primitive: A data type without any properties (or in its primitive form) is called a primitive data type. There are seven kinds of primitive data types:
  • String: A string is written in quotes and represents a sequence of characters.
  • Number: This data type is used to denote numeric values.
  • Boolean: The values of true and false kinds are represented by the boolean data type.
  • Null: All nonexistent values are represented by the null data type.
  • Undefined: This data type is used in the case of a declared but unassigned JavaScript variable. The type and value for this data type are undefined.
  • BigInt: This data type is used for storing large numbers that are over the normal limit.
  • Symbol: A unique value can be stored using this data type. This data type was first incorporated in the ES6 version.
  • Non-primitive. It should be noted that all of the above data types store single values, so there was a need for a data type that can store complex and multiple values. This is where the non-primitive data types come in. Two main non-primitive data types are:
  • Array: This non-primitive data type comes in handy when one has to sort similar values together. Each value in an array has its unique position, known as its index. Another property of an array is that it can entertain any type of data type. The indexing starts from 0 in an array, so the first element in any array will be arr[0].
  • Object: To store a collection of data, the 2nd non-primitive data type, the object is used.

23. What are the different checks of equality in JavaScript?

There are two main checks of equality in JavaScript, “==” and “===”. The “==” is an operator that is used to check the equality of two values while the “===” operator is used to compare the values as well as the operand’s data type.

24. Can you write normal text with JavaScript?

The innerText property in JavaScript allows us to insert normal text dynamically. Basically, what it does is that text is set in the HTML element. With this property normal text like “hello world” can be written using JavaScript. The working of innerText is somewhat in resemblance to that of the innerHTML, but the purpose is different for both.

25. What do you know about the creation of objects?

There are multiple approaches toward object creation in JavaScript, and each of these has its unique procedure and properties.

  • Creation of objects by the use of object literal.
  • Object creation by the use of Object.create().
  • Creation of object by the use of ‘new’ keyword.
  • Constructed type objects.

26. What do you know about the creation of arrays?

There are multiple approaches toward object creation in JavaScript, and each of these has its unique procedure and properties.

  • Creation of arrays using an array literal.
  • Array creation by generating an instance of an array.
  • Constructed type arrays.

27. What are the two sides of JavaScript, and how would you differentiate between them?

JavaScript has two sides, namely the server-side JavaScript and the client-side JavaScript. A developer is called a full stack JavaScript developer if he can develop both sides.

Client-side JavaScript refers to the part of the code that runs on the client machine. The client-side JavaScript incorporates simple, predefined programming language and objects that are necessary for successfully running the codes in a browser. The client-side JavaScript is interpreted by the browsers at runtime, and it is directly embedded into the HTML pages.

Server-side JavaScript refers to the part of the code that is run on the main server that is providing the web pages. Deployment of the server-side JavaScript is performed after complete compilation. Node.js – in simple words – is server-side JavaScript. The developer can use Node.js to provide server-side functionality to your JavaScript-based projects.

28. Where are cookies stored in a computer hard drive?

The location where cookies are stored on a hard disk can vary based on the operating system and the respective browser. Usually, in Windows, the Netscape navigator stores cookies in a txt file named cookies.txt using the path: c:\Program Files\Netscape\Users\username\cookies.txt

On the contrary, the Internet Explorer names its cookie file as username@website.txt in the following directory: c:\Windows\Cookies\username@Website.txt

Cookies are basic elements, so JavaScript interview questions cannot be completed without them.

29. How are mathematical constants and operations performed in JavaScript?

There are many mathematical operations that a developer can do.

In addition to being able to perform basic math using operators in JavaScript, we also have the Math object. This object allows us to access mathematical constants and do more complex calculations. JavaScript uses a dot to note a particular child of the Math object. All constants are predefined, so they exist as part of basic JavaScript.

30. How can you incorporate a date displayed using JavaScript?

The JavaScript comes integrated with the Date object, which comes in handy when we want to display a day, a month, or a year separately or all together on a webpage. The timezone can also be adjusted using the Date object in JavaScript.

31. What is the use of the number object in JavaScript?

Numeric values can be represented using a Number object and created using the Number() constructor.

32. Describe the usage of Boolean object in JavaScript?

The Boolean object is used whenever a value needs to be represented in two states — either “true” or “false”. If we need to know whether anything is “yes” or “no,” we should use the boolean function.

33. What are falsy and truthy values in JavaScript?

The terms truthy and falsy are often used in a boolean context, such as an if…else statement. There are eight false values in JavaScript:

  • false
  • 0 (zero)
  • -0 (minus zero)
  • 0n (BigInt zero)
  • ”, “”, “ (empty string)
  • null
  • undefined
  • NaN

I consider anything that is not present in the above list as true.

34. Differentiate between a statically and a dynamically typed programming language

1) Statically typed programming languages do type-checking at compile-time. Dynamically typed programming languages do type-checking at run-time or execution time.

2) In statically typed languages variable assignments are static and cannot be changed. In dynamically typed languages variable assignments are dynamic and can be altered.

35. What is pass by reference and pass by value?

When we use the pass by value, the system generates a copy of the original variable, and all of the changes incorporated into the copy cannot affect the original variable. So basically in pass by value, the information is copied to a different variable and the copied one is passed. When we use pass by reference, no copy of the original variable is generated, and the actual parameter is passed. This means that in pass by reference, all changes made will directly affect the original variable.

36. What is an I.I.F.E. in JavaScript?

I.I.F.E is the abbreviation for an Immediately Invoked Function Expression. The Immediately Invoked Function Expression is basically a JavaScript function that automatically runs on the very instant that it is defined. Basically, an Immediately Invoked Function Expression is used due to privacy concerns. No one from outside can access the variables that have been defined inside an Immediately Invoked Function Expression.

37. What do you understand about prototypal and classical inheritance?

As the name suggests, inheritance refers to the acquisition of functionality or properties from a parent program to be incorporated into a new one. This feature allows for a code to be reused.

Classical Inheritance is a process that allows one class to extend the methods of another class. Prototypal Inheritance is a process that allows one object (or a function constructor) to extend the methods of another object.

38. How would you describe the usage of deferred scripts in JavaScript?

It is often noticed by web browser users that in case of a slow internet connection or due to an extensive script, it takes a very long time to execute the HTML of the web page. The defer attribute tells the browser not to wait for the script. Basically, the script with defer:

  • never block the page.
  • always execute when the DOM is ready (but before DOMContentLoaded event).

39. What do you understand about a prompt box in JavaScript?

When we want the user to enter something (a number, word, etc.), we use a prompt box. The prompt() function displays a dialog window in which the user is required to provide information.


JavaScript Interview Coding Questions

40. Perform a check to verify if an object is an array. Discuss two scenarios, one for being an array and one for not being an array

  • Array
const books = [
"The Trial", 
"Metamorphosis", 
"Bible", 
"The Reluctant Fundamentalist"];
let result = Array.isArray(books);
  • Not an Array
let answer = "Javascript interview coding questions";
let result = Array.isArray(answer);

41. Can you explain the difference between the 2 relations in JavaScript? ‘ “21”+3+30 ‘ and ‘ 21+3+“30” ‘

21+3+“30”= 2430          	“21”+3+30 = 21330

42. According to you what should be the output of the following codes

  • Code 1
function func(){
for(var i = 0; i < 69; i++){
setTimeout(()=> console.log(i),8000);
}
}
func2();
  • Code 2
function func(){
setTimeout(()=>{
console.log(x);
console.log(y);
},3000);
 
var x = 7;
let y = 42;
}
func1();

Code 1 = 69
Code 2 = 7, 42

43. Write down the output of the following code

function runFunc(){
console.log("2" + 2);
console.log("X" - 5);
console.log(6 + "-6" + "9);
console.log("Java" - "script" + 6);
console.log("ECMASCRIPT"+ "6");
}
runFunc();

=22, NaN,6-69,NaN,ECMASCRIPT6

44. Write the code to convert the given string to a number: “5862324”

var s = "5862324" ;
var n = Number (s) ;

We first assign a value to a variable and then convert it to a string.

45. Guess the output of the following code

( function (g) {
return ( function () {
console.log (g) ;
g = 45 ;
} ) ()
})(97);

=97

46. Modify the following code to your best ability

// Whenever we call the function bigFunc, a size 800 array is generated, 
we need a code that does not recreate the same array.
function bigFunc(element){
let newArray = new Array(800).fill('jaydevs');
return newArray[element];
}
 
console.log(bigFunc(699)); // Array is created
console.log(bigFunc(770)); // Array is created again

= Modified code:

function bigFunc(){
  let newArray = new Array(800).fill('jaydevs');
  return (element) => newArray[element];
}
 
let getElement = bigFunc();
getElement(699);
getElement(770);

47. Modify the following code to your best ability

//Modify the code to output 0 and 1 after one second.
 
function randomFunc(){
for(var j = 0; j < 2; j++){
setTimeout(()=> console.log(j),1000);
}
}
randomFunc();

=

function randomFunc(){
  for(var j = 0; j < 2; j++){
  (function(j){
      setTimeout(()=>console.log(j),1000);
	})(j);
  }
}
randomFunc();

48. Take the following array: [9,7,5,3,1] and perform 3 right rotations with a function. The rotations will look like [1,9,7,5,3], [3,1,9,7,5], [5,3,1,9,7]

function rotateRight(arr,rotations){
  if(rotations == 0) return arr;
  for(let i = 0; i < rotations;i++){
	let element = arr.pop();
	arr.unshift(element);
  }
  return arr;
}
rotateRight([9,7,5,3,1], 3);

49. What should be the code for dynamically inserting new components?

<html>
<head>
<title>dynamic insertion</title>
<script>
	function addNode () { var newP = document. createElement("p");
	var textNode = document.createTextNode(" This is other node");
	newP.appendChild(textNode); document.getElementById("parent1")
            .appendChild(newP); }
</script>
</head>
<body> <p id="parent1">firstP<p> </body>
</html>

50. Write the JavaScript code to turn an object into an array

let qwerty = { dob: "12", name: "John", work: "developer",age: "27" };
 
console.log(Object.keys(qwerty));

51. Write down the output of the following code

const b = [10,9,8,7,6,5,4,3,2,1];
 
for (let i = 0; i < 10; i++) {
setTimeout(() => console.log(b[i]), 1000);
}
 
for (var i = 0; i < 10; i++) {
setTimeout(() => console.log(b[i]), 1000);
}

= 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined.

52. State the output of the following code

var Output = (function(x)
{
Delete X;
return X;
}
)(0);
console.log(output);

The output would be 0. As the delete operator does not affect local variables.

53. Elaborate the output of the following code

var O = { Foo : 5};
var Output = (function()
{
delete O.foo;
return O.foo;
}
)();
console.log(output);

The output should be undefined.

54. Elaborate the output of the following code

var Employee =
{
company: 'lmn'
}
var Nate = Object.create(employee);
delete Nate.company Console.log(nate.company);

The output would be lmn.

55. What should be the output of the following code

var Foo = Function Bar()
{
return 9;
};
typeof Bar();

The output would be Reference Error because only one reference variable can be used as a name.

56. In JavaScript, how can we differentiate between a non-integer and an integer?

This syntax is used to check for an integer

Number.isInteger(value)

57. Show the multiplication of the numbers 3 and 9 using JavaScript

function multiply(a) {
  return function(b) {
	return a * b;
  }
}
 
multiply(3)(9);

58. Perform a check for anagrams on two strings

var firstWord = "Javascript";
var secondWord = "scriptJava";
 
isAnagram(wordOne, wordTwo); // true
 
function isAnagram(one, two) {
  //Change both words to lowercase for case insensitivity..
  var a = one.toLowerCase();
  var b = two.toLowerCase();
 
  // Sort the strings, then combine the array to a string. Examine the outcomes.
  a = a.split("").sort().join("");
  b = b.split("").sort().join("");
 
  return a === b;
}

59. Elaborate the string charAt() method in JavaScript

In JavaScript, whenever we need a character returned from an index, the string charAt() method is used. Index values are between 0 and n-1, it has to be noted that index values can never be negative. We can see the working of this method from the following code:

var str="javascript interview questions";	
document.writeln(str.charAt(11));

Output = “ i ”

60. Write the JavaScript code to change the color of a HTML document

<script> 
document.body.bgColor="cyan"; 
</script>

Advanced JavaScript Interview Questions or Senior JavaScript Developer Interview Questions

Here are the most common JavaScript advanced interview questions and their expected answers:

61. What does an “object” refer to in JavaScript?

Any independent unit that has its distinct properties and a specific type is known as an object in JavaScript. To simplify an object, let us compare it to something from the physical world. Let’s take the example of a tennis ball, it is an object with certain properties. It has a unique color, weight, and distinct material that it is made up of. Similarly, the objects that are defined inside JavaScript have their own distinct features. Variables in JavaScript are also objects, multiple values can be contained in a variable.

62. How can you explain the BOM?

BOM is an abbreviated form of Browser Object Model, basically, the Browser Object Model allows users to convey their message to the browser. A window is the initial object of a browser and the Browser Object Model consists of five objects, namely the screen, location, history, navigator, and document.

63. How can you explain the DOM?

The Document Object Model is abbreviated as DOM in JavaScript, the HTML document is represented, accessed, and changed using a Document Object Model. A Document Object Model is created by the browser whenever a web page is loaded, standard operating procedures are defined by the Document Object Model that dictates how a document can be accessed on a web page. In simpler words, we can say that a Document Object Model is just a standard method that allows us to retrieve, remove, or alter the elements of an HTML.

64. Differentiate between a document and a Window

The most straightforward differences between a window and a document are as follows:

65. Is there any way to access the history in JavaScript?

JavaScript has a special object that can be used to load the previous history of a browser. The object that is used is written and used in three ways. It can be observed as follows:

history.forward ()
history.go ()
history.back ()
  • The first one is used to go to the next web page.
  • The second one is used to retrieve the previously viewed web page.
  • The last command is used to dictate to the browser the number of pages backward or forward in the history that the user wants to navigate to. The command takes the user to the desired web page in history. A positive number may be used to scroll forward and a negative number to go backward.

66. How are functions created in JavaScript?

In order to perform the desired operation, a function that can execute that operation needs to be defined. The benefit we get from this is that we don’t have to keep repeatedly writing code every time we want to perform that operation. Once we create a function, it can be later evoked and reused if necessary with just a click. JavaScript function syntax:

function functionName(Parameter1, Parameter2, ..)
{
    // Function body
}

To build a function in JavaScript, we must first use the keyword function, followed by the name of the function and the parameters contained in parenthesis. The function’s body is the part of the function contained by curly braces.

  1. Can you state what is the event.preventDefault() and event.stopPropagation(), and how do they differ from each other?
  • event.preventDefault() is used to stop the browser’s default behavior when performing an action.
  • event.stopPropagation() is used to prohibit event propagation as defined in the capturing/bubbling phase of an event’s flow in the browser.

68. In JavaScript, can the cursor be set to wait? If no why not and If yes, how?

Yes, we can put the cursor to wait in JavaScript. There is a “cursor” property that is used to set a cursor in a browser to wait. The purpose can be achieved using the following code line inside our code:

<html>
<div style="width: 100px; height: 100px; background: blue; cursor: wait">
A mouse over this blue patch will show you the wait cursor.
</div>
</html>

69. What can you tell about the debugger keyword or a debugger statement?

The debugger is used as a stopping tool in JavaScript, or in other words, we can say it is a breakpoint for the code. The debugger intends to stop the program propagation at any stage that it is applied. Nowadays, JavaScript debuggers are present in modern browsers by default that can be turned on and off, making errors visible to the user.

70. Describe the purpose of strict mode in JavaScript

In the ES 5 revision, a new feature was added to JavaScript, known as the strict mode. With this feature, strict operation conditions can be applied to a function or a program. Strict mode converts some JavaScript silent errors into throw errors.

In JavaScript, ‘use strict’ indicates that the code should be performed in ‘strict mode’. This makes it easier to write good and secure JavaScript code.

71. Describe exports and imports in JavaScript

In JavaScript modules, the export statement is used to export functions, objects, or primitive values from one module so that they can be used in other programs (via the ‘import’ statement).

Modular code in JavaScript is possible thanks to the import statement (and also, code reuse and sharing).

72. Explain event bubbling in JavaScript

Event bubbling is a bottom-to-top model, this means that the event will start in the most relevant element (trigger element) and then move up the DOM hierarchy until it reaches the root of the document.

73. What is meant by Local storage and Session storage?

Local storage and Session storage are the two mechanisms that are used to store required data in the client’s browser.

  1. Local storage object — Stores data with no expiration date.
  2. Session storage object — Stores data for one session (data is lost when the browser tab is closed).

Using localStorage and sessionStorage is a great alternative to cookies. Extra benefits of localStorage and sessionStorage:

  • Data is kept locally and is inaccessible to the server. The security issues with cookies are solved as a result.
  • The syntax is simple and straightforward.
  • The storage limit is about 10MB

74. Define a first-class function

First-class functions can be used in the same way as ordinary variables. First-class functions can do any task that a variable can. First-class objects can:

  • Be passed as arguments to functions;
  • Be returned by functions;
  • Be stored in a variable;
  • Be stored in some data structure; and,
  • Hold their own properties and methods.

75. What do you know about the Revealing Module Pattern?

The JavaScript design pattern known as the Revealing Module Pattern enables users to organize their JavaScript code into modules, which improves code organization and helps to make certain information either secret or public.

76. Explain the process of creating private class features in JavaScript

A private function can only be used within the parent module or function. Class fields are public by default, but private class features can be created by using a hash # prefix.

77. Explain the usage of the operator “this” in JavaScript

The “this” keyword or operator allows us to:

  • Use the same functions in various execution environments. It means that a function can be called for various objects after it has been defined by using the “this” keyword.
  • Identifying the object when we call a method in the current execution context.

78. Define the concept of recursion

Recursion is the process of defining a problem or the solution to a problem in terms of itself.

Syntax of a recursive function:

function recursion() {
    if () { //desired command
        return;
    }
    // recursive step codes
}
recursion();

One key advantage of recursion is that it allows complex tasks to be completed in a few lines of code. As a result, the codebase looks simple and elegant, while also removing chunky and bulky codebases.

79. How are the var, const, and let keywords different from each other in JavaScript?

The keywords var, const, and let are used for declaring variables in JavaScript.

  • The var keyword supports global scope or function level and can be reassigned.
  • The scope of let is block level. The let keyword and the same variable name cannot be re-declared multiple times. Here the block is confined to the curly braces ({ and }).
  • The scope of const is the same as let, block level — block is confined to the curly braces ({ and }). Const keyword and the same variable name cannot be repeatedly declared.

80. What do you know about type coercion?

Type coercion is the automated or implicit conversion of values from one data type to another. There are many kinds of implicit type coercions, for example, string to number, boolean to number, number to string, etc.

81. How can you explain the apply() and call() methods?

In call() method, JavaScript uses a specified object to invoke a function, this can be explained with the following example:

function sayHi(){
  return "Hi " + this.name;
}
    	
var obj = {name: "John"};
    	
sayHi.call(obj);
    	
// Returns "Hi John"

The apply() method is just like the call() method. The only difference between how they work is that call() expects all parameters to be passed in individually, while apply() expects an array of all of our parameters.

82. What do you understand about currying in JavaScript?

In JavaScript, currying refers to an advanced technique that allows us to convert multiple argument functions to a function that takes only one argument. In simple words, if we have a function of the form f(x,y,z), it is converted into f(x), f(y), and f(z) functions, where x,y and z are arguments of the function f. In the curried function, we simply wrap a function inside a function.

83. What do you understand about higher-order functions in JavaScript?

Higher-order functions are regular functions that take one or more functions as arguments and/or return a function as a value. Higher-order functions are useful when we want to customize the behavior of a function or when we want to use that function repeatedly.

84. What is external JavaScript and its advantages?

External JavaScript refers to JavaScript code that is placed in a file apart from the HTML code. External JavaScript code is written and used similarly to internal JavaScript code. The file should have the “.js” extension. Note: The external code must not be placed between the tags, the code will not work.

  • It separates HTML and code.
  • The external JavaScript code is reusable and very simple to read. Developers can work together on JavaScript and HTML with external JavaScript.
  • Cached JavaScript files can speed up page loads

85. Define memoization

The process or programming technique that caches the results that were previously computed in order to enhance the performance of a function is called memoization. The parameters of a memoized function are used for indexing the cache every time the function is called.

Simply put, memorizing means memorizing or storing something in memory.

86. Explain the role of a constructor function in JavaScript

A constructor is a function that builds and initializes an object instance of a class. If we need a large number of objects that use the same methods and have alike properties, we use the constructor function. So, a constructor’s aim is to create a new object and set values for any existing object properties. When an object is created with the new keyword, a constructor is invoked. When a constructor gets invoked the following sequence of operations takes place:

  • A new empty object gets created.
  • This keyword starts referring to the new object, which becomes the current instance object.
  • The new object is then returned as the constructor’s return value.
function Applicant(age,experience,role){
  this.age = age;
  this.experience = experience;
  this.role = role;
}
var applicant1 = new Applicant(29,”two years”, "DBA");
console.log(Applicant1);
 
var applicant2 = new Applicant(69, “twenty years”, "HRM");
console.log(Applicant2);

87. How would you explain an arrow function?

Arrow functions are frequently used as callbacks of native JS functions such as map, filter, or sort. Their name comes from the use of => in the syntax. Arrow functions are simpler to write and read since they are less verbose. In addition, because they are always anonymous, arrow functions can be used in places where named functions are not allowed.

The difference between a normal function and an arrow function can be seen in the following example:

  • Normal Function
hello = function ()
{
   return “javascript coding interview questions”;
}
  • Arrow function
hello = () =>
{
  return “javascript coding interview questions”;
}

88. Explain your understanding of the usage of promises in JavaScript

JavaScript promises are a highly useful feature that allows us to perform asynchronous JavaScript code. Asynchronous operations frequently occur in applications. It may take the form of API requests, delayed data processing, and many other things. Instead of blocking code execution until the data loads, you can define them as promises, allowing code execution to proceed with other parts of the code. So, when the promises are complete, you can use the data in them.

A promise has three states:

  • Pending: The promise is still in the works
  • Fulfilled: The promise resolves successfully and returns a value
  • Rejected: The promise fails with an error

89. How can you explain classes in the ES6 JavaScript version?

In JS, classes are used as templates for objects, these templates always require a constructor function. Before ES6, it was difficult to create a JavaScript class. However, in ES6, we may use the class keyword to build the class. We can add classes in our code by using a class expression or a class declaration.

class Employee{
  constructor(gender,name,age,role){
	this.gender = gender;
	this.name = name;
	this.age = age;
	this.role = role;
  }
 
  // Methods can be directly added inside the class
  getDetails(){
	return '
        Gender: ${this.gender}, 
        Name: ${this.name}, 
        Age:${this.age}, 
        Role:${this.role}';
  }
}
 
let employee2 = new Employee("Male", “Jake”, 33, CEO);
employee2.getDetails();
// Returns Gender: Male, Name:Jake, Age: 33, Role:CEO

90. What are generator functions in JavaScript?

  • In JavaScript, functions “run until return/end.”
  • Generator Functions “run until yield/return/end.”

When a Generator Function is called, as opposed to a standard function, it produces a Generator Object that contains the whole Generator Iterable that may be iterated using the next() method or for…of loop.

Every next() call on the generator executes every line of code until it finds the next yield and temporarily suspends execution.

Normally, generator functions are built with yield expressions. Each yield within the generator function acts as a checkpoint before the next execution cycle begins. Each execution cycle is triggered by the generator’s next() method.


Some More JavaScript Interview Questions and Answers

91. What do you understand about a pure function?

A pure function is a function which:

  • Given the same input, will always provide the same output.
  • Produces no side effects.

Pure functions are also incredibly independent — they are simple to move, refactor, and reorganize in your code, making your programs more responsive to future changes.

92. Define a cookie, and why is it needed?

Cookies were created to deal with the problem of “how to remember information about the user”. A cookie is basically a segment of data that is stored in the client machine’s hard drive. The data is recorded and stored in the form of small text files that contain information about the user profile. Basically, the browser needs to remember some information about the user to facilitate in the future: whenever the user visits the web page again, the cookies provide the basic information about the user.

93. Elaborate event capturing in JavaScript

Event capturing is the scenario in which events propagate from wrapper elements to the target element that initiates the event cycle. The flow of propagation in event capturing is from top to bottom. If we had an event related to the browser’s Window, it would be the first to execute. In the following example, the event capturing will be performed in the following order: Window, Document, DIV 2, DIV 1, and lastly the button.

94. Explain the same-origin policy in JavaScript

The same-origin policy is a browser-standard security measure. Basically, the policy in JavaScript that stops the out-of-the-domain requests is known as the same-origin policy. The term “origin” usually refers to a “domain.” It prohibits different origins from interacting with one another, hence preventing attacks like Cross Site Request Forgery.

95. When does JavaScript return a syntax error?

When there is an error in the basic syntax of a code, JavaScript will return a syntax error.

96. How can you perform an email validation in JavaScript?

An email is a string (a subset of ASCII characters) separated into two parts by the “@” symbol. The domain part contains the following ASCII characters:

  • Uppercase (A-Z) and lowercase (a-z) English letters.
  • Digits (0-9).
  • Characters ! # $ % & ‘ * + – / = ? ^ _ ` { | } ~
  • Period, dot, or full stop (.) with the restriction that it cannot be either the first or last letter of the email or follow one another.

The domain name [for example, com, org, net, in, us, info] is made up of letters, digits, hyphens, and dots.

We use a regular expression /w+([.-]?w+)*@w+([.-]?w+)*(.w2,3)+$ to get a valid email id.

97. How do innerHTML and innerText differ from each other?

The main difference is that the first one can process an HTML tag in a string but the innerText cannot.

98. Name a few JavaScript frameworks

The most common Javascript frameworks are Angular, Vue, and React.

99. Explain the concept of hoisting

The default behavior in JavaScript is that whenever functions or variables are declared, they move up to the top in their scope. Example:

  •  Without Hoisting
x = 5;                                   	
alert ( ‘ x = ‘  +x);          	
var x;
  • With Hoisting
var x;
x = 5;
alert ( ‘ x = ‘ + x);

100. What do you understand about a callback function?

When a function has been passed into another function, it becomes a callback function. It is a function that is executed within another function to fulfill the desired action.

101. How can each word in a string be reversed?

By using the reverse() method, each word in a string can be reversed.

102. How many methods of emptying an array can you think of?

There are four methods that can empty an array:

  1. arrayList.length = 0
  2. arrayList = []
  3. while(arrayList.length){arrayList.pop();}
  4. arrayList.splice(0, arrayList.length);

103. How would you define scope chain and scope?

The scope defines which functions and variables are present in the code and what is their accessibility status. Scope chains refer to the currently available scopes in a code.

104. What are object prototypes in JavaScript?

An object prototype is basically a mechanism that allows an object to inherit features from some other object.

105. Does JavaScript encounter any errors? What are the types?

Yes, JavaScript encounters errors. There are three types of errors, logical errors, load time errors, and run time errors.

106. What is the weakSet in JavaScript?

WeakSet is used to store a collection of objects. WeakSet throws an error when you try to add data types other than objects.

JavaScript weakSet methods:

  • add() — add a new object to the end of WeakSet object.
  • delete() — delete the specified object from the WeakSet object.
  • has() — indicate whether the WeakSet object contains the specified object element.

107. What is the weakMap in JavaScript?

WeakMaps allow objects to be extended from the outside without interfering with garbage collection. A WeakMap can be used whenever we want to extend an object but can’t because it’s sealed — or from an external source.

108. What is the reason for wrapping the entire content of a JavaScript source file in a function block?

In JavaScript, wrapping the entire content of a source file generally comes with immediately invoking it. The function is called an Immediately Invoked Function Expression, or IIFE. It is usual practice to wrap browser JavaScript with an IIFE to keep variables and functions private and not pollute the global scope. We can use an IIFE to expose only the APIs we wish to expose (by returning them in an object) and hide the rest.

109. What do you mean by escape characters in JavaScript?

When working with strings, we can find that some characters apostrophes, ampersands, double quotes, etc.) break the program. To protect the application from breaking, special characters are written, in JavaScript. In JavaScript, the backslash ( \ ) is an escape character. An escape character allows us to output characters that we would not normally be able to, usually because the browser might read it differently than we intended.

110. Define a Temporal Dead Zone

In the ES6 version, JavaScript returns a ReferenceError when the const or let variable is tried to be accessed before declaring the variable. The declaration of a variable and its creation take some time, this time period is called the Temporal Dead Zone.

Tags:

dev-info
logo-single