×

Top 25+ JavaScript Interview Questions You Must Prepare in 2021

Gowtham K  Print   20 min read  
11 Sep 2021
 
17.4K Views

Today, JavaScript is a programming language which you can be used in place of C#, Java, Php or any other object-oriented languages. JavaScript can run in a browser, server-side or on any device using a program known as JavaScript Engine. This article contains most commonly asked interview questions and answers in a JavaScript or front-end technologies Interview.

  1. What is JavaScript?

    Ans. JavaScript is an object-based programming language, mostly it used as a client-side programming language with the HTML page to add some behavior for it.

    JavaScript initially created as a browser only language, but now it can be executed on the server or any client which has a JavaScript Engine. The product like Node.js, MongoDB, jaggery.js, ASP and many more uses server-side JavaScript.

    In the browser, JavaScript can do many things as given below:

    • Manipulating the HTML element.

    • React to a user action, like running some event while user clicks on the mouse or by using the keyboard.

    • Send request to the remote server.

    • Downloading and uploading the files.

    • Get and Set cookies and handling the client-side storage (local and session storage).

    Major Advantage of using the JavaScript

    • Full integration with HTML/CSS .

    • Supported by all major browser which is enabled by default.

  2. What is ECMAScript?

    Ans. ECMAScript is a scripting language standardized by ECMA International in ECMA-262. Languages like ActionScript, JavaScript, and many more scripting languages are used ECMAScript, among these JavaScript is a well know client-side scripting language and an implementation of ECMAScript, since the standard was published. The latest version is ECMAScript6.

  3. What are the data types supported by JavaScript?

    Ans. JavaScript variables are dynamically typed, which means there is a data type but it will not bound to a particular type, example while initializing the variable it can be string type but later It can also assign to a numeric value.

    The data types supported by JavaScript are:

    • Undefined

    • Null

    • Boolean

    • Object

    • String

    • Symbol

    • Number

  4. What is the difference between undefined and not defined?

    Ans. Considers below example

    var x;
    console.log(x);
    
  5. Now in the console, we will get a message x is ‘undefined’ which means the variable is declared and memory is created but the value is not assigned to it.

    console.log(y)
    

    In this case, you will get a message like ‘not defined’ because the variable y is not created, and memory is not allocated for it and we try to reference the variable.

  6. What is the use of typeof operator?

    Ans. The typeof is a unary operator which means it takes a single operand in a statement or expression, it is used to check the data type of its operand in the form of a string.

    var x=10;
    console.log(typeof (x))
    

    It will print number in the console

    var x = 10;
    console.log(typeof (x) == 'number')
    

    From the above code if the typeof x is number, so from the expression it will print true in the console.

  7. What is the instanceof operator?

    Ans.  instanceof operator checks whether the object is an instance of a class or not.

    function Country(name){this.name=name}; 
    var country = new Country("India");
    console.log(country instanceof Country) // return true
    

    It will also consider inheritance

    let arr = ['apple', 'orange', 'grapes'];
    console.log(arr instanceof Array); //prints true in console
    console.log(arr instanceof Object); //prints true in console 
    

    arr is an array, but it also belongs to object, because array prototypal inherits from object.

  8. What is strict mode?

    Ans. “use strict” is not a statement but a literal expression which is supported by ECMAScript version 5. This statement instruct browser to use the strict mode, which is a safer future in JavaScript. It will eliminate some JavaScript silent errors.

    Example

    "use strict";
     x = 10; // this will give error
    

    The above statement will give an error because in strict mode the variable should be declared before it is used.

    The “use strict” expression can be in global scope as well as local scope

    Global scope

    const employee = { name: "Ram", age: 25 }
    employee.name = "Raju" // it is possible 
    use strict";
    x = 10; // this will give error
    

    local scope

    x = 10; // This will not give error. 
    myFunction();
    function myFunction() {
     "use strict";
     y = 15; // This will give error
     }
    
  9. Explain String in JavaScript?

    Ans. The group of character or textual data is called string, in JavaScript, there is no separate type for the character, even a single character will be stored as a string. In JavaScript, the string can be enclosed with single quotes or double quotes

    var str = 'hello';
    console.log(str);//print hello
    
  10. What are the differences between search() and indexOf() ?

    Ans: The differences between search and indexOf methods are given below:

    search()
    indexOf()
    It is used to find a specified value and returns the position of the match, the value can be a string or regular expression
    It is used to find a specified value and returns the position of the match, the value should be a string, it won’t accept a regular expression
    var m = /e/;
    
    var m = /e/;
    
    var str = "apple";
    str.search(m)//return 4
    
    var str = "apple";
    str.indexOf(m)//return -1
    
  11. What are the differences between indexOf() and lastIndexOf() ?

    Ans: The differences between indexOf and lastIndexOf methods are given below:

    indexOf()
    lastIndexOf()
    It will return the index of the first occurrence of specific text in a string
    It will return the index of the last occurrence of specific text in a string
    var str = 'Hello find me test me';
    str.indexOf('me') // return 11
    
    var str = 'Hello find me test me';
     str.lastIndexOf('me') // return 19
    
  12. What are the differences between substr() and substring()?

    Ans: The differences between substr and substring methods are given below:

    substr()
    substring()
    It is used to return the characters in a string beginning at the specified index and returns the number of characters based on length provided
    It is used to return the characters in a string beginning at the specified index and returns the number of characters based on length provided-1
    var x = "hello";
    console.log((x.substr(1, 4) == "ello"))
    

    It will print true in the log

    var x = "hello"; 
    console.log((x.substring(1, 4) == "ello"))
    

    It will print false in the log

    var x = "hello";
    console.log((x.substring(1, 5) == "ello"))//print true in console
    
  13. What are the differences between array and object?

    Ans: The differences between array and object are given below:

    Array
    object
    The array uses the numbered indexes to access the element in it
    The object uses the named indexes to access the members in it
    You should use an array when you want the element name to be number
    You should use an object when you want the element name to be a string
    It is an ordered collection
    It is a collection of unorder properties
  14. What is the Self-Executing Function?

    Ans. The self-executing function will execute right after it has been defined. The advantage of using it is, it will execute the code without declaring any global. Mostly it will be used to attach event listeners to DOM elements and another initialization work.

     
     (function () 
     {
     //function body
     })();
    
    
  15. What is the arrow function?

    Ans. The arrow function will support in JavaScript only after ES6 or above, it is a short way to write function expression. The conventional way of writing a function

    function add(a, b) {
     return a + b;
     }
    console.log(add(1, 2));//3
    

    Using arrow function

    add = (a, b) => { 
    return a + b 
    }
    console.log(add(1, 2));//3
    
  16. How to find the browser which is running the web page?

    Ans. The window object navigator is used to find the browser which is currently running the web application.

    var browsername = navigator.appName;
    console.log(browsername); 
    
  17. How to redirect the user to a new page?

    Ans. We can use the window object location to redirect the user to the new page

    window.location.href="https://www.dotnettricks.com/"
    
  18. What is the output of below code?

    var num = "10";
    (function () {
     console.log("Original Number " + num);
     var num = "50";
     console.log("New Number " + num);
     })();
    

    Ans. Original Number undefined

    New Number 50

    Reason: You will expect the original number will take the value from the outer scope, but the salary value was undefined, because of hoisting.

  19. What is DOM?

    Ans. DOM is a W3C (World wide web consortium) standard, when the HTML page loads in the browser, the browser creates the DOM (Document object model). It defines the HTML element as an object and allows scripts to dynamically manipulate the content, and the structure of the document.

    HTML:

    <!DOCTYPE html>
    <html lang="en">
    <body> 
     <h1>Document Object Model</h1>
    </body>
    </html>
    

    In DOM, every HTML is an object, Nested tag are “children”, the text inside a <h1> is an object as well

    The DOM Tree of objects

    The DOM represents HTML as a tree structure of tags. Here’s how it looks in browser inspect element

  20. What is BOM?

    Ans. BOM (Browser Object Model) which provides interaction with the browser, the default object of the browser is a window. Various property provided by windows is a document, history, screen, location, navigator.

  21. What is the NaN property in JavaScript?

    Ans. NaN property depicts “Not-a-Number” value. It shows a value that is not a legal number. One type of a NaN would return a Number. If you want to check if a value is NaN, isNaN() function is used. It is important to note that isNaN() function transforms the given value to a Number type; later on, it equates to NaN.

  22. What is the usefulness of the window object?

    A browser’s history object could be used to switch to history pages like back and forward from the existing page or another page. 3 methods of history object are as follows:

    1. history.back() – This method loads the previous page.
    2. history.forward() – This method loads the next page.
    3. history.go(number) - Its number may be positive (for forward) or negative (for backward). It will load the provided page number.
  23. What is the functioning of timers in JavaScript?

    Ans. Timers are useful to operate a piece of code at a specific time or iterate the code in a specific interval. The same is performed by using functions like setInterval, setTimeout, and clearInterval. Timers are executed in a single thread. Therefore, maybe queue up and there may be a waiting time for execution..

    The setTimeout(function, delay) function is useful for starting a timer that calls a specific function after the stated delay. The setInterval(function, delay) function frequently operates the provided function in the stated delay and only stops when canceled. The timer gets to know when to stop with the clearInterval(id) function.

  24. What are the various types of errors in JavaScript?

    Ans. Here are the 3 types of errors in JavaScript:

    • Runtime errors: These are the errors that occur due to misuse of the command within the HTML language.
    • Load time errors: These errors occur while loading a web page. An example includes improper syntax errors that produce the errors dynamically.
    • Logical Errors: These errors come up because of the bad logic carried out on a function with a varied operation.
  25. What is the ‘Strict Mode in JavaScript? How you can enable it?

    Ans. Strict Mode inserts some compulsions to JavaScript. In the strict Mode, JavaScript displays errors for a segment of code that did not display an error previously. However, it may be tricky and potentially insecure. Moreover, Strict Mode also resolves some errors that may obstruct the efficient working of the JavaScript engines.

    You can enable Strict mode by inserting the string literal “use strict” above the file. Look at the following example to get a better idea:

    function myfunction() {

    "use strict;"

    var v = "This shows implementation of a strict mode function";

    }

  26. Explain the difference between .call() and .apply()

    Ans. The function .apply() and .call() are very identical in their usage but comes with a minor difference. The .call() is employed whenever the programmer knows the number of the function’s arguments. This is because they have to be stated as arguments within the call statement. Conversely, .apply() is employed whenever the number is unknown. Also, this function .apply() needs that the argument should be an array. The key difference between these two functions is how the arguments are passed to the function.

  27. How is DOM used in JavaScript?

    Ans. DOM (Document Object Model) is accountable for how different objects in a document interrelate with each other. It is useful for developing web pages that contain objects like links, paragraphs, etc. Such objects can be executed to contain actions like add or delete. Furthermore, DOM is also useful to equip a web page with extra capabilities. The use of API provides a benefit compared to other prevailing models. If you deeply go through the javascript tutorial, you can know more about DOM.

  28. What is the role of deferred scripts in JavaScript?

    Ans. The parsing of HTML code during page loading is by default paused until the script has not halted executing. The webpage is delayed if the server is slow or the script is chiefly heavy.

    When using the Deferred, scripts would delay execution of the script until the HTML parser is operating. It decreases the web pages’ loading time and they get showcased faster.

  29. What are the different functional components in JavaScript?

    Ans. Functional components are important topics covered in a javascript Course. Two types of functional components in JavaScript are –First-class functions and nested functions.

    i. First-class functions: These functions in JavaScript are used as first-class objects. Usually, this means that such functions can be passed in form of arguments to other functions. Moreover, they are returned as values from other functions or assigned to variables, or they can be saved in data structures.

    ii. Nested functions: Those functions that are defined within other functions are termed Nested functions. Whenever the main function is invoked, nested functions are called.

  30. What are the different ways to access HTML element in JavaScript?

    Ans. The following DOM Methods are used to capture the HTML element and manipulate it.

    1. getElementById('idname') - > This function is used to select the HTML element based on ID

      <!DOCTYPE html>
      <html>
      <head>
       <meta charset="utf-8" />
       <title></title>
      </head>
      <body>
       <label id="myelement"></label>
       <script>
       document.getElementById('myelement').innerHTML = '<h3> Welcome </h3>'
       </script>
      </body
      </html>
      
    2. getElementsByClassName('className') - > This function is used to select the HTML elements based on the class name in DOM, it will return all matched HTML element with respect to the class name.

      <!DOCTYPE html>
      <html>
      <head>
       <meta charset="utf-8" />
       <title></title>
      </head>
      <style>
       .lblMsg {
       color: #000;
       }
      </style>
      <body>
       <label id="myelement" class="lblMsg"></label>
       <script>
       document.getElementsByClassName('lblMsg')[0].innerHTML = '<h3> Welcome </h3>'
       </script>
      </body>
      </html>
      
    3. getElementsByTagName(‘HTMLtagname’) - > This function is used to select the HTML elements based on the Tag name in DOM, it will return all matched HTML element with respect to the Tag name.

      <!DOCTYPE html>
      <html>
      <head>
       <meta charset="utf-8" />
       <title></title>
      </head>
      <style>
       .lblMsg {
       color: #000;
       }
      </style>
      <body>
       <label id="myelement" class="lblMsg"></label>
      <script>
       document.getElementsByTagName('label')[0].innerHTML = '<h3> Welcome </h3>'
      </script>
      </body>
      </html>
      
Summary

I hope these questions and answers will help you to crack your JavaScript Interview. These interview Questions have been taken from our new released eBook JavaScript Interview Questions & Answers. This book contains more than 110 JavaScript interview questions.

This eBook has been written to make you confident in JavaScript with a solid foundation. Also, this will help you to turn your programming into your profession. It's would be equally helpful in your real projects or to crack your JavaScript Interview.

Buy this eBook at a Discounted Price!

JavaScript Interview Questions & Answers ebook
Share Article

Take our free skill tests to evaluate your skill!

In less than 5 minutes, with our skill test, you can identify your knowledge gaps and strengths.

Training Schedules
+91 9999123502
Accept cookies & close this