Javascript Interview Questions – Prepare JavaScript Interview Questions

In this JavaScript Guide, We will see JavaScript Interview Questions and Answers with Explanations. We will learn, How to solve some common Javascript Interview Questions, as well as try to understand some Advanced Javascript Interview Questions.

So, Let’s begin : One by One –

A Modern Collection of JavaScript Interview Questions



JavaScript Interview Questions and Answers

Let’s start the list of Questions but first, To refresh our mind, here is one of the Triky Javascript Interview Coding Questions –

What's the Output of : console.log(5.0 == “5” == new Boolean(true) == “1”); JavaScript Statement?
========== (4) ==========

========== (3) ==========

========== (2) ==========

========== (1) ==========

========== (0) ==========

(Don’t get confused, the above lines are just to stop you from checking its answer directly).

Almost 14 people out of 15 say, the above console.log() statement would print false. But, it prints true;

The reason is behind 2 things – (I) JavaScript Operator Precedence, and (II) Associativity.

 

Now if you don’t know, what are these 2 terms, I wouldn’t go in-depth of these but here’s a Quick note for you –

Precedence : The operator precedence defines the order (or sequence) in which the expression would be executed.
Example : 2 + 3 + 4 * 5
In above expression, multiplication is performed first. Hence, the result will be 2 + 3 + 20 = 25, NOT 45

Associativity : The Operator Associativity defines the direction (right to left or left to right) in which the entire expression would be evaluated.
Example : 2 + 3 + 4 * 5

In this expression, the Associativity of both the operators Plus + and Multiply * are Left-to-Right, however, The Precedence of + is 4 and * is 3 (that is higher). So the multiplication would be evaluated first from Left-to-Right and its result would take its place. Then the + Addition operation would be processed and we get 25.

Now, Let’s come back to the Solution of the above JavaScript Interview Question to find the outcome of console.log() statement. We will take the help of below JavaScript Operator Precedence and Associativity table –

 

JavaScript Operator Precedence and Associativity define how an expression would be evaluated.
Table: JavaScript Operator Precedence and Associativity

 

As you can see from the above table, The associativity of new operator is Right-to-Left while the associativity of == Equality operator is Left-to-Right.

Let’s try to understand- How JavaScript engine executes this statement in 3 phases –

[The Statement]  5.0 == “5” == new Boolean(true) == “1”

[Part 1]  5.0 == “5” == true == “1”

The precedence of new operator is higher than the precedence of == equality operator, hence the new operator would be calculated first, and we get true in place of the Object creation : new Boolean(true).

[Part 2] true == true = “1”

We got true in place of 5.0 == “5” of Part 1, as its the working functionality (or say behavior) of == Equality operator.

In JavaScript, If the Left and Right operands of == operator are of Different types, the JS engine tries to convert them to the same type before comparing a number to a string. And, converts the string to a numeric value. That’s why it sees it as 5.0==5.0 and its absolutely true. And we get a smaller part 3 –

[Part 3] true == “1”

Same thing will happen here too, that I’d explained in part 2. After calculating this expression, the JS engine return finally returns –
true
That’s the outcome of above console.log() statement.

It was a Javascript Interview Question, asked in Paytm Technical Interview for Web Developer @Delhi, India. Let’s try to understand other Simple and Advanced JavaScript Interview Questions with Answers –


Mostly Asked JavaScript Interview Questions

 

Question 1) What do you know about JavaScript map() function?

The map() function is available with a JavaScript array. Using this function, we get a new array, as we apply a transformation function on each and every element of the array. Here is the Syntax for JavaScript array map function-

 

Syntax :

yourArray.map((theElement){

      process(theElement)

      return processedValue
}) // returns new array with each element processed...

 

Explanation :
Suppose, there are few unwanted characters entered into some Phone numbers. And, We need to remove them. So, Instead of removing the character by iterating and finding, we can use JavaScript map() function to perform the same operation and get desired results as another array.
Practice Basic and Advanced JavaScript Interview Questions
JavaScript is enriched with a number of useful concepts and features ranging from Functions to Events, Cookies to Arrays and Animations to RegEx. If you really want to be an expert in JavaScript, then here’s a Complete JavaScript Course 2021: From Zero to Expert course on Udemy that you should check to be a lot better in JavaScript.

Example :

var data = ["9898878777g", "887766w9988", "98798879877", "7987897897"];

var reg = /[a-z A-Z]/;         // It's RegEx : A Regular Expression

var filteredData = data.map((elem) => {return elem.replace(reg, "")});

console.log(filteredData); 

// Output :  ["9898878777", "8877669988", "98798879877", "7987897897"]

 


Question 2) How to use JavaScript filter() function?

The filter() function is a major part of the JavaScript Functional Programming concept. The filter() function is similar to map() as it also processes each element of the array and returns a new array.

The length of the original array can be slightly greater than or equal to the filtered array. Because, the condition passed to the JavaScript filter() function may exclude a few/zero inputs in the resultant array.

Syntax :

theArray.filter(( yourElement ) => {
      return true/false
})

 

Explaining :
In the above example, yourElement is the data of the array and true/false should be returned to indicate inclusion/exclusion of filtered element from the function.

 

Example :

Let’s take a simple example and filter the array of website-names that starts with given conditions. Suppose, we need to filter all website-names starting with ‘s’ from the array:

var websites = ["geeksforgeeks.com", "skype.com", "shubhamklogic.com", "javatpoint.com"];

var filteredData = websites.filter((theElement) => {
   return theElement.startsWith('s') ? true:false;
});

console.log(filteredData); 

// Output : ["skype.com", "shubhamklogic.com"]

By the way, the return statement is returning either true or false, as we have used the Ternary operator in JavaScript. It’s similar to using an if-else.


Question 3) What would be the Outcome of these calls? –

console.log( yourSquare(7) );   // Call- 1

function yourSquare(n) { 
      return n * n; 
}


console.log( mySquare(7) );      // Call- 2
 
var mySquare = function(n) { 
      return n * n; 
}

From Call- 1, we will get 49. It’s okay.

Call-2 gives us the following result-

ERROR- Uncaught TypeError: mySquare is not a function

We get an Error because, In JavaScript, if you define a function as a variable, the variable name will be hoisted but you cannot access it until JS engine encounters its definition.

Now, in order to fix the above code, just define the mySquare() function before the Call- 2, Like this :

console.log(yourSquare(5));          // Call- 1

/* ... Some JS Code ... */

function yourSquare(n) { return n * n; }

 
var mySquare = function(n) {    // Defining mySquare()
  return n * n; 
}

console.log(mySquare(5));            // Call- 2

 


Question 4) .call() in JavaScript : How to use call() in JavaScript?

If you have ever noticed the JavaScript code of any famous libraries such as bootstrap, font-awesome, or other, you might be seen these live in it.

Technically speaking, these modules allow something called Currying using which we can compose the functionality or task into a number of sub-functions. A good JavaScript developer can easily tell you about these three terms at any time.

 

Practice Common JavaScript Interview Questions and Understand it's solutions

 

The .call(), .apply(), .bind() and similar other functions play an important role in Function handling in JavaScript. If you want to learn all about all such useful functions and other concepts practically, here are 50 Projects in 50 Days JavaScript, HTML, CSS course on Udemy, that you should check.

At its core, these are basically the prototype methods of functions to alter the behavior and achieve something. In other words, You can –

  • Use .bind() methods when you want that function to later be called with some certain configuration or context, useful in events.
  • Use .call() or .apply() methods when you want to call the function immediately, with updation of the context.
Example :
Suppoach, you are given a task to write JavaScript Function to calculate Area, Circumference, and other things of a Circle. Here, is a possible solution of it –
var theCircleLib = {

    pi: 3.14,

    area: function(r) {
        return this.pi * r * r;
    },

    circumference: function(r) {
        return 2 * this.pi * r;
    }
};

 

When you’ll run it with a given radius r = 5, you will successfully get this –

theCircleLib.area(2); 
12.56

 

Some moment later, you are told to use constant pi with 5 decimals precision. But, we had just used with 2 decimal precision:  3.14, not the 3.14159

Don’t worry, JavaScript .call( ) function to the rescue. Just call theCircleLib( ) function in this way –

theCircleLib.area.call( { pi: 3.14159 }, 2 );

 

And, you’ll successfully get the output with 5 decimal precision –

12.56636

 

In short, the .call() function can take these 2 arguments :

  • The Context, and
  • Function Arguments.

Question 5) .apply() in JavaScript : How to use apply() in JavaScript?

The .apply() function is same as .call() except we have to pass the Function arguments as a List. To understand it better, Let’s assume, we have a Cone, and we need to calculate its volume –

var cone = {

    pi: 3.14,

    theVolume: function(r, h) {
        return this.pi * r * r * h/3;
    }
};

 

Now, if you want to invoke theVolume using .call() function, here is how to use .call() in this case –

cone.theVolume.call({pi:3.14159}, 3, 6)
56.54867

 

And, with .apply() function, here’s how to do the same –

cone.theVolume.apply({pi: 3.14159}, [3, 6]);
56.54867

 

The difference between .call() and .apply() in this simple example, is just that we passed the values not just as regular values separated by comma (with .call() statement), but as a List. See the brackets : [ 3,6 ]  in .apply() statement above.


Question 6) .bind() in JavaScript : How to use bind() in JavaScript?

The .bind() function attaches a brand new this to a given function. If, you don’t know what is this in JavaScript? Then, understand it in this Quick note –

  • If we consider this inside a function, then the value of this is determined by how a JavaScript function is called.
  • If we consider this outside a function, then in the Global execution context, this refers to the Global object whether in strict mode or not.
All the evaluations of this happen with something known as runtime binding, and that’s a whole different concept.
Now, coming back to the .bind() function –
In bind’s case, the function is not executed instantly like .call() or .apply(). Here’s an example in continuation of above –
var newVolume = cone.theVolume.bind({pi: 3.14159}); // It's now a call to theVolumn, but just the binding of pi with its value

// After some time in mid of the year...

newVolume(3,6);                                     // Now pi is 3.14159, as we already binded it earlier.

Now, you might be thinking, What is the actual use of .bind() function?

Technically speaking, It allows us to inject a context into a function that returns a new function with updated context. In simple words, this variable will be just like a variable, supplies by the users. This is very useful and handy while working with JavaScript events.

Question 7) What are Objects in JavaScript? How do you use them?

Many beginners even Intermediate JavaScript developers know Objects like this –

var books = { javascript: 98, sql:95, java: 91, react:85 };

But, that NOT an Object, It’s a Map in JavaScript. Map stores Key and its Value as a pair. JavaScript Object provides a special feature of storing anything as a Value. Here, anything means anything, whether it’s an array, list, function or even another Object.

 

  • Creation :
    In JavaScript, we can create an Object in multiple ways, like these –
var books = {};                         // Technique 1
var books = new Object();               // Technique 2

 

 

  • Initialization :
    We can set properties and values in multiple ways, like these –
var myBook = new Object();           // Technique 1

myBook.name = 'JavaScript';
myBook.category = 'Programming';
myBook.price = 120;

var myBook = {                       // Technique 2
    name: 'JavaScript',
    category: 'Programming',
    price: 120
};

 

In the above example, Technique 2 is also known as Object Initializer, which is nothing but another way to create and initialize objects. It is basically a comma-separated list of zero or more pairs of property names and its values, enclosed in curly braces { } ends with a semi-colon ;

  • Traversing
for (i of Object.keys(myBook)) {
	console.log(i+'-->'+myBook[i]);
}

// Prints -
// name-->JavaScript
// category-->Programming
// price-->120

 

Question 8) What is the Output of the Code –

const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
    setTimeout(function () {
        console.log("Index: " + i + ", value: " + arr[i]);
    }, 3000);
}

It’s basically a Tricky JavaScript Interview Question asked by Amazon and shared by a user on Reddit.

The Outcome would be –

Index: 4, value: undefined
Index: 4, value: undefined
Index: 4, value: undefined
Index: 4, value: undefined

 

The reason for such an Outcome is because the setTimeout function creates a function (the closure) that has access to its outer scope, which is the loop that contains the index i.

After 3 seconds go by, the function is executed and it prints out the value of i, which at the end of the loop is at 4 because it cycles through 0, 1, 2, 3, 4 and the loop finally stops at 4. Here, the arr[4] does not exist, which is the reason, you get undefined.

Anyone, who has less command over JavaScript topics: Closures, setTimeout and scoping, would feel difficult to understand it thoroughly.

  • Solution : Pass the required paremeter
    To print the index numbers of the constant array, you need to pass the essential parameters to the function. Here, we passed ‘i‘ as the required parameter –
const myArr = [10, 12, 15, 21];

for (var i = 0; i < myArr.length; i++) {

      // pass in the variable 'i' so that each function has access to the correct index -

    setTimeout( function(my_local_i) {

     return function() {
          console.log( 'The index of this number is : ' + my_local_i );
     }

  }(i), 3000);         // passed 'i' with timing 3 sec. ( or 3000 milisec. )
}

 

Once you’ll pass the required parameter ‘i’, and run the give code snippet, you will get this output –

The index of this number is : 0 
The index of this number is : 1 
The index of this number is : 2 
The index of this number is : 3

 

What Next? 

So far, we learned a number of JavaScript Interview Questions with Solutions. We understood the Concepts and Logic used behind the code.

It was just a starter guide, a number of other Popular JavaScript Technical Interview Questions based on other topics such as Closure, Array, String, Promises, will be added to this list in upcoming days, so make sure you save this Link of the page or bookmark it in your browser.

And, If you want to learn all JavaScript concepts step-by-step with examples, then, here are some Best JavaScript Books and Useful resources that will help you to be a JavaScript expert –

Better Resources (100%)

 

JavaScript Concepts (Read Next)


P.S.** : If you want to learn fundamentals and become a master in JavaScript, you must check : JavaScript 2121 – From Zero to Expert course on Udemy by Jonas Sch., in which he explained almost each & every minor-major Topic of JavaScript in the simplest way.

P.S.S.*** : If you are already working with JavaScript for the past few time, and really want to enhance your programming skills into Product / App development, then do check the Modern React.js with Redux course on Udemy by Stephen G.

I hope, you found this JavaScript Interview Guide helpful. Please, don’t forget to share it with your favorite social media friends. And, If you have any doubt/query, then please do comments, I’ll try my best to clear all your doubts within a day.

Leave a Comment