Advanced JavaScript Interview Questions and Answers – Explore now & Lead tomorrow!

Free Web development courses with real-time projects Start Now!!

The first part of DataFlair’s JavaScript Interview Questions was more inclined towards the testing of your theoretical knowledge of JavaScript. This article on JavaScript interview questions and answers follows a practical approach towards the language and will play a major part in cracking your JavaScript interview.

After completing all the topics of JavaScript tutorial series, these JavaScript interview questions and answers should not be much trouble for you. And, I assure you that after practicing this set of JavaScript interview questions and answers, you will definitely feel more relaxed in your interview.

JavaScript Interview Questions and Answers for Experienced Professionals

Top JavaScript Interview Questions and Answers

Here are some of the lastest JavaScript interview questions for experienced professionals. Practice them and get your dream job.

Q 1. Is it possible to write a multi-line string in JavaScript?

Ans. Yes, JavaScript provides the facility to write a String in multiple lines using the following three approaches:

  • Using backticks
var string = `line1
line2
line3`;
  • Using + operator
var string = “line1” +
“line2” +
“line3”;
  • Using \ (backslash)
var string = “line1 \
line2 \
line3”;

Grab the complete knowledge of JavaScript Strings Methods

Q 2. Discuss a way to convert the string of any base to integer in JavaScript?

Ans. We can convert a string of any base to the integer if we wish with the help of the JavaScript built-in method called parseInt(). This method has two parameters: string and radix. The second parameter is optional and used when you want to get the integer equivalent to the radix as the base. The default value is 10 for decimals values.

parseInt(“9d”, 16) // 157

Q 3. While creating a webpage, a programmer wanted to print the output “This is DataFlair’s JavaScript tutorial”. Instead, he encounters a SyntaxError in the browser console. What went wrong, and can he fix it? He used the following statement:

var string = 'This is DataFlair's JavaScript tutorial'

Ans. The programmer wrote confusing statements for the JavaScript interpreter. He has two options to resolve this error:

  • Using escape characters – He can use \’ instead of ‘ after DataFlair. This will inform the script that the inverted comma is part of the string and the string is going to continue.
var string = 'This is DataFlair\'s JavaScript tutorial'
  • Using double inverted commas – The programmer can use double inverted commas to wrap the string rather than the single inverted comma.
var string = 'This is DataFlair's JavaScript tutorial'

Time to learn everything about JavaScript Characters

Q 4. What are the different methods to empty a JavaScript Array?

Ans. You can use the following techniques to produce an empty array:

  • You can redefine the older array as an empty array.
emptyArray = [ ];
  • You can set the length of a predefined array to zero.
definedArray.length = 0;
  • You can update the array to contain zero elements with the help of the JavaScript splice() method.
definedArray.splice(0, definedArray.length);
  • You can remove all the elements of the array using array methods: pop() or shift().
while(definedArray.length){
        definedArray.pop();
} //pop() method

Or

while(definedArray.length){
        definedArray.shift();
} //shift() method

Don’t forget to check – JavaScript Array

Q 5. Determine the output of the following code.

var courses = ["JavaScript","Java","C","C++","Python"];
delete courses[2];
console.log(courses.length);

Ans. The output of the code is 5. This is because the delete operator does not affect the length of the array as the operator deletes only the value present at the position. At the deleted index, we get the value undefinedx1 (in Chrome) or just undefined/ empty. Thus, if we tried the statement console.log(courses), we will get (5) [“JavaScript”, “Java”, empty, “C++”, “Python”].

Q 6. Explain the role of closures in JavaScript.

Ans. In JavaScript, the script creates a closure at the time of function creation. It is a local variable that stays in the memory even after the function completes its execution. It has access to the variables in three scopes: variable in its own scope, variables in the enclosing function’s scope, and global variables. Closures are crucial in JavaScript to ensure the privacy of variables, that is, to create private variables. Since JavaScript has no access modifiers, closures allow the programmer to create variables that are not directly accessible.

Master the concept of JavaScript Closures and its implementation

Q 7. Consider the code snippet below. What will the console output be and why?

(function(x) {
return (function(y) {
    console.log(x);
})(2)
})(1);

Ans. The output of the function is 1, even though we never set the value of x in the inner function. The reason behind this is that the above function is a closure. Thus, the inner function has access to the outer function’s variables. In the example code, since the interpreter didn’t find the value of x in the inner function, it searched for its defined value in the outside function. That’s where it found x to have a value of 1.

Q 8. Is it possible to remove the content from a website? If yes, how?

Ans. Yes, there are a few possible ways to remove content from the website at will.
The easiest way is to hide the content from the browser you want to remove. The display property of the JavaScript style attribute helps us achieve the task. Whenever we add any content to the webpage, its default display sets to block (display: block). We can change the value to none (display: none). This will prevent the content from showing in the browser window. This approach only hides the details, it will still be available in the source code, and you can access it from the Elements window.

Another way to do so is by removing the element node corresponding to the content. This technique completely removes the data from the webpage as well as the code. We can do this by .removeChild() method. Or if we are dealing with an array (including a NodeList), then we can easily empty the array, and get the same result.

The decision of selecting the appropriate method for the situation depends on the programmer and his/ her needs.

Q 9. Write the JavaScript code to print the following output on your console window.

Array: [“DataFlair”, 2019, 1.0, true]

Ans. The code to print the following output in the console window is as follows:

<html>
  <body>

    <script>
        var array = ["DataFlair", 2019, 1.0, true];
        var msg = "Array: [";
        for(var i = 0; i < array.length-1; i++){
            msg += array[i] + ", ";
        }
        msg += array[array.length-1] + "]";
            console.log(msg);
    </script>

  </body>
</html>

Q 10. What are the possible ways to write a function isInteger(value), that determines if the value is an integer?

Ans. EcmaScript 6 introduced a new function, Number.isInteger(), to determine whether a value is an integer or not. But the specifications before EcmaScript 6 have no such function. In fact, there are no integers; numeric values are always in the form of floating-point values.

The following are some of the functions you can declare to check for an integer pre-EcmaScript-6:

  • Using the bitwise operator:
function isInteger(value) { return (value ^ 0) === value; }
  • Using the Math object:
function isInteger(value) { return Math.round(value) === value; }

In this approach, Math.ceil() and Math.floor() methods are equally capable to implement the function.

  • Using the typeof and strict equality operator:
function isInteger(value) { return (typeof value === 'number') && (value % 1 === 0); }

There is another way for the problem, but it only works with small numeric values.

function isInteger(value) { return parseInt(value, 10) === value; }

The problem with this process: it fails when the value of “value” becomes quite large. It is because parseInt() converts the first parameter to a string before parsing the digits. Thus, with a large value, the string will be represented in exponential form (e.g., 1e30). Once parseInt() reaches the character ‘e’, it stops parsing, and thus returns the value 1 (in this case). So, this method is fine as long as you only need to work with small numbers. Otherwise, you may want to consider the above techniques.

Get to learn the different methods to write a number in JavaScript

Q 11. Write a program to calculate the length of an associative array.

Ans. The JavaScript code to count the length of an associative array is as follows:

<html>
  <body>
    <script>
      //an associative array
      var associativeArray = {one: "DataFlair", two:"JavaScript", three: 435, four: true};
      var count = 0;
      //calculating the length of the array
      for (arrayValue in associativeArray){
        count = count + 1;
      }
      console.log(count);
    </script>
  </body>
</html>

The code produces the output 4 in the browser console.

Any doubts in the JavaScript interview questions and answers till now? Share them in the comment section.

Q 12. What is a possible dilemma with typeof obj === “object” to determine if obj is an object? How can we avoid this?

Ans. The above statement is a reliable way of checking if obj is an object, but in JavaScript, null is also an object. Thus the following statements will return true in the console, surprising most of the developers:

var obj = null;
console.log(typeof obj === "object");

As long as you keep this problem in mind, you can easily use the typeof operator to determine whether obj is an object or not. Remember, this method will return false if obj is a function, true if obj is an array.

An alternative condition that returns false if obj is null, array, or function, and returns true for objects is this:

console.log((obj !== null) && (obj.constructor === Object));

Must Learn – How to Create JavaScript Objects

Q 13. What would the following code return?

console.log(typeof typeof 1);

The output of the code above in the console will be ‘string’. The value returned by typeof 1 is ‘number’; typeof ‘number’ will return a string.

Q 14. Write a simple function, indicating whether or not a string is a palindrome.

The following code checks whether the two strings are palindromes or not.

<html>
  <body>

    <script>
        function isPalindrome(str) {
                str = str.replace(/\W/g, '').toLowerCase(); //gets a lowercase string
                var string = str.split('').reverse().join(''); //reverses the string
                //checks if the string and the reversed strings are the same
                if(string == str)
                        return "A palindrome"
                else
                        return "Not a palindrome"
        }
        console.log(isPalindrome("level"));
        console.log(isPalindrome("levels"));
    </script>

  </body>
</html>

The output in the browser console shows the following output:

A palindrome
Not a palindrome

Q 15. Explain the process of document loading.

Ans. Loading a document means getting it ready for execution on the system. When there is a running document on the system, the document loads on the browser. The application (browser) allows the JavaScript engine to do two tasks:

  • Look for all the properties, given to the object.
  • Include all the property values, used in the content that is being rendered for the page about to load.

To load the document immediately, it is good practice to add the <script> tag inside the <body> tag. The following program loads the document immediately and returns the OS details of the user:

<html>
  <body>
  <H1>JavaScript used</H1>

    <script>
        <!-- Comments to hide js in old browsers
        document.write("Give the version: " + navigator.appVersion)
        document.write(" of <b>" + navigator.appName + "</b>.")
        // end of the comment section -->
    </script>

  </body>
</html>

Q 16. Consider the following code. What will the output be, and why?

(function () {
    try {
      throw new Error();
    } catch (x) {
      var x = 1, y = 2;
      console.log(x);
    }
    console.log(x);
    console.log(y);
})();

Ans.

The output of the code in the console is as follows:
1
undefined
2

In JavaScript, all the var statements are ‘hoisted’ (without their value initialization) to the top of the global/ function scope it belongs to, even inside a try-catch block. Though, the error’s identifier is only visible inside the catch block. The equivalent code looks like this:

(function () {
    var x, y; // outer variables, hoisted
    try {
        throw new Error();
    } catch (x /* inner x */) {
        x = 1; // inner x, not the outer one
        y = 2; // there is only one y (in the outer scope)
        console.log(x /* inner x */);
    }
    console.log(x);
    console.log(y);
})();

Explore the concept of JavaScript Function Scope and different types of JavaScript Functions

Q 17. Consider the following code snippet:

for (var i = 0; i < 5; i++) {
  var btn = document.createElement('button');
  btn.appendChild(document.createTextNode('Button ' + i));
  btn.addEventListener('click', function(){ console.log(i); });
  document.body.appendChild(btn);
}

What is the output in the console when the user clicks on “Button 4” and why?

No matter what button the user clicks, the output will always be 5. This is because when the onclick event invokes (when the user clicks any of the buttons), the ‘for’ loop is already finished and the value of the variable i is set to 5. All this happens at the time the document loads; the onclick event occurs later.

Q 18. When should one use Arrow functions in ES6?

Ans. The thumb rule for functions in ES6 and beyond is as follows:

  • Use functions in the global scope and for Object.prototype properties.
  • Use class for object constructors.
  • Use => everywhere else.

The reason for using arrow functions almost everywhere is due to the following reasons:

  • Scope safety – Consistent use of arrow functions guarantees to use the same thisObject as the root. If even a single standard function callback gets mixed-up in with a bunch of arrow functions, there’s a chance the scope will become confusing.
  • Compactness – Compared to regular functions, arrow functions are easier to read and write. They also reduce the length of the JavaScript code.
  • Clarity – With almost everything defined in an arrow function, a regular function is extremely noticeable. You can always look up the next-higher function statement to see what the thisObject (root object) is.

Q 19. What are IIFEs?

Ans. IIFEs (Immediately Invoked Function Expressions), also called Self-Executing Anonymous Functions, are functions that execute immediately after their definition. These are also a design pattern that contains two major parts:

  • The first part is an anonymous function with a lexical scope enclosed within the Grouping operator (). This restricts the access of variables within the IIFE idiom and prevents it from polluting the global scope.
  • The second part of IIFE creates the immediately executing function expression, through which the JavaScript engine will directly interpret the function.

The syntax of an IIFE is as follows:

(function () {
    statements
})();

All the variables defined inside an IIFE are not visible to the outside scope.

Let’s revise the concept of JavaScript Variables

Q 20. How can you remove duplicate values from a JavaScript array?

Ans. There are multiple ways to remove duplicate values from an array; the most common ones are as follows:

  • By using set

This is the easiest way to remove duplicate values from an array. Set is a built-in JavaScript object that stores the unique values in another array. The following program will create an array with unique values:

function uniqueArray(array) {
        var newSet= new Set(array);
            var newArray = Array.from(newSet);
        return newArray;
}
var arr = [1,5,2,4,1,6]
console.log(uniqueArray(arr));
  • By using filter

This approach removes all the duplicate values from the array by applying a filter on it. The filter() method requires three arguments: element (we want to check for duplicity), index (of the element) and array (containing duplicates). The following program returns a unique array:

function uniqueArray(arr){
        var newSet = arr.filter(function(elem, index, self) {
            return index == self.indexOf(elem);
        })
        return newSet;
}
var arr = [1,5,2,4,1,6]
console.log(uniqueArray(arr));
  • By using for loop

This method is a little tiresome and not always recommended. But you can create a unique array by creating an empty array and only adding new values that are not already present in the array. The code implementation is something like this:

function uniqueArray(dups_names) {
    var unique = [];
    arr.forEach(function(i) {
        if (!unique[i]) {
                unique[i] = true;
        }
    });
    return Object.keys(unique);
}
var arr = [1,5,2,4,1,6]
console.log(uniqueArray(arr));

Summary

This was all in the tricky JavaScript interview questions and answers. We tried to cover all the core JavaScript technical interview questions which are mostly asked in a JavaScript interview.

I hope you are clear with all the JavaScript interview questions and answers. If you have come across with queries regarding any JavaScript interview question or answer, mention them in the comment section.

Next article in the JavaScript DataFlair Tutorial Series for you – JavaScript Project on Photo Gallery

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *