30 Javascript Intermediate Interview Questions in 2021: Part 2

30 Javascript Intermediate Interview Questions in 2021: Part 2
30 Javascript Intermediate Interview Questions in 2021: Part 2

Introduction

Javascript was developed by Brenden Eich and is the most popular language in the field of Web Development. The language is used to create dynamic web pages and add functionality to the raw HTML and CSS code. These Javascript interview questions are a stack that a developer can go through for the last-minute revision.

Below are Intermediate Javascript Interview questions that will help you crack your interviews and get your dream job. Companies like Netflix, Capital One, Nagarro, and many more are now hiring JavaScript developers.

We have listed the top 30 Intermediate Javascript Interview questions asked by most of the companies during the interview.

Intermediate Javascript Interview Questions

Question 1) What is the use of !! Operator in JS? 

Answer: The double-not operator is used to coerce the value on the right to boolean. This variable returns a boolean value and calculates the truth of a given matter.
For example : !!(true) will give us true, because !true is false and !false returns true.
This is how the double-not variable works.

Let’s consider the given code for more clarity :

console.log(!!true);


Output :

true

Question 2)How do you clone an object?

Answer:

We can create a clone of an object using 3 ways

  1. To create a spread using {…} syntax.
  2. To create an object using Object.assign()
  3. By using JSON.stringify() and JSON.parse() methods.

We can use the object.assign() and spread to create a shallow copy, not a deep copy. This means that nested objects are not copied. Whereas the JSON method carries a deep copy of the object.

The following example covers all three methods to create a copy of an object.

blog banner 1
const student= {
    name: 'CN',
  dob: '23/08/2000'
};


// using spread ...
let s1 = {
    ...student
};

// using  Object.assign() method
let s2 = Object.assign({},student);

// using JSON
let s3 = JSON.parse(JSON.stringify(student));

Question 3)Explain the role of deferred scripts in Javascript?

Answer: It is a boolean attribute used to specify that the script is executed when the page has fully been parsed. When we use defer, the script is automatically downloaded in parallel with page parsing. Once the page is fully parsed, the script will get executed.

The critical thing to remember is that the ‘defer’ can be used only for external scripts. 

Question 4)What is Event Bubbling?

Answer: Event Bubbling is a method of event propagation in HTML. It is the propagation of the event which occurs from the origin to the root.

The concept of event bubbling is used where event handlers are involved. While performing the event flow of a webpage, event bubbling is used. It is a sequence of calling event handlers when one element is nested in another element.

Question 5) What will be the output of the given code?

var output = (function(x) {
  delete x;
  return x;
})(0);

console.log(output);

Answer: The output of the above code will be 0. Delete operator is used to delete a property of an object hence not affecting the local variable ‘x’ in the above case. 

Question 6)Define Singleton pattern in Javascript.

Answer: The singleton pattern in javascript is also known as the Javascript design pattern. It is used to wrap the code in a logical unit that can be accessed using a single variable. It restricts the instantiation of a class to a single object. They serve as a shared resource namespace that isolates implementation code from the global namespace to provide a single access point for functions. We can implement a singleton as follows : 

var MySpace = {};
MySpace.Singleton = (function() {


  var singleton; 

    function constructor() {
    var Var1 = "CN";
    var Var2 = [1,2,3,4,5];

    function privateMethod1() {
      // codebody
    }

    function privateMethod1() {
      // codebody
    }

    return {
      attribute1: "CN,”
      publicMethod: function() {
        alert("CN");// some code logic
      }
    }
  }

  return {
 
    getInstance: function() {
      //instance already exist then return 
      if(!singleton) {
        singleton = constructor();
      }
      return singleton;          
    }          
  }

})();  


console.log(Myspace.Singleton.getInstance().publicMethod());

The singleton class maintains a static reference to the lone singleton instance and returns a reference from the static getInstance() method.

Question 7) Write code to merge two javascript objects dynamically.

Answer: We can use the following two methods to merge two javascript objects dynamically : 


Method 1: Using ES6, Object.assign method

const mergeabc = (toObj, fromObj) => Object.assign(toObj, fromObj);

Method 2: Without using the built-in function

function merge(toObj, fromObj) {
  // Make sure both of the parameters is an object
  if (typeof toObj === 'object' && typeof fromObj === 'object') {
    for (var pro in fromObj) {
      // Assign only own properties not inherited properties
      if (fromObj.hasOwnProperty(pro)) {
        // Assign property and value
        toObj[pro] = fromObj[pro];
      }
    }
  }else{
  throw "Merge function can apply only on object";
  }
}

Question 8) Why is eval() considered dangerous in Javascript?

Answer: eval() is considered a dangerous function in javascript as it leaves your code vulnerable to malicious code injections and slows down the code’s performance. If we run eval() with a string that could be affected by a malicious party, we may end up running malicious code on the user’s machine with the permissions of your webpage. We should avoid it in most cases.

Question 9)What is the difference between an attribute and a property?

Answer: Attributes are defined in HTML, whereas properties are defined in DOM. It is preferred to use properties than simple HTML attributes as an attribute is only ever a string, and no other data type is available. Properties can be accessed using jQuery’s prop method and by interacting with the object in vanilla JS.

Question 10)What is the Temporal Deadzone in ES6?

Answer: In ES6, let bindings are not subject to Variable Hoisting, which means that let declarations do not move to the top of the current execution context. They are referencing the variable in the block before the initialization results in a ReferenceError (contrary to a variable declared with var, which will just have the undefined value).

The variable is in a “temporal dead zone” from the start of the block until the initialization is processed.

console.log(aVar); // undefined
console.log(aLet); // causes ReferenceError: aLet is not defined
var aVar = 1;
let aLet = 2;

 

Question 11) Explain what a single-page app is and how you can make it SEO-friendly.

Answer: Web applications tend to be highly interactive and dynamic, allowing the user to perform actions and receive a response to their action. 

 The browser loads the initial page from the server and the scripts (frameworks, libraries, app code) and stylesheets are required for the entire application.

The advantages: The application is more responsive, and hence users do not see the flash between page navigations. Fewer HTTP requests are made to the server, as the same assets do not have to be downloaded again for every page load.

Clear separation of the concerns between the client and the server; you can quickly build new clients for different platforms (e.g., mobile, chatbots, smartwatches) without having to modify the server code. You can also change the technology stack on the client and server independently, as long as the API contract is not broken.

Question 12)What is meant by ‘repaint and reflow’? How does it affect your application?

Answer:

Reflow is simply the process of re-analyzing the positions of elements on a page. When you change a div’s height, the font, or set a property using the style attribute, the browser has to recalculate to re-render the web page. 

What triggers reflow: 

  1. When we resize the window 
  2. When we change the font
  3.  When we change the font size 
  4. When we try to add animations of DOM elements
  5.  When we try to Add/remove a stylesheet 
  6. When we calculate offsetWidth or offsetHeight 

Reflow is an expensive process and it should be avoided. 

Repaint happens when you change the element’s appearance without any significant changes. So that includes changing the color, background color, border color, or setting the visibility: hidden. From a performance standpoint, a repaint is less expensive than a reflow.

Question13) What will be the output of the given code?

let i;
for (i = 0; i < 3; i++) {
  const log = () => {

  console.log(i);
}
  setTimeout(log, 100);
}

Answer

for() loop iterates 3 times. During each of these iterations, a new function log() is being created, which calculates the variable i. After that setTimout() schedules an execution of log().When for() loop cycle completes, i variable has a value of 3. The second phase happens after 300ms: The 3 scheduled log() callbacks are called by the setTimeout() method. log() method reads the present value of the variable i, which is 3 and it logs to console 3.

That’s why the output is 3, 3, and 3.

Question 14) What is the OOPs concept in Javascript?

Answer: Object-oriented programming is a programming paradigm that uses abstraction to create models which are based on the real world. It uses techniques like paradigms, including modularity, polymorphism, and encapsulation. 

In Javascript, we have several objects included in the core. Some of them are Math, Object, Array, and String. In javascript, the concept of classes is covered by functions.

Question 15) What is an unsigned right shift operator in Javascript?

Answer: In Javascript, the unsigned right shift operator is used in the array extra’s method to ensure that the length property is an unsigned 32-bit integer. The length property of array objects is described in the specification as:

Every Array object has a length property whose value is always a non-negative integer less than 232.

This operator is the shortest way to achieve it; internally, array methods use the ToUint32 operation, but that method is not accessible and exists on the specification for implementation purposes.

Question 16) What is the reason to choose the Quicksort algorithm over the default sort() method in Javascript?

Answer: Default sort() in JavaScript uses insertion sort by V8 Engine of Chrome and Merge sort by Mozilla Firefox and Safari.

But, this is not suitable if you need to sort a large number of elements. So, the solution is to use Quicksort for a large dataset.

Quicksort Algorithm is based on the divide and conquer approach, which means that it divides the array into smaller parts based on some conditions and performing sorting operations.

Question 17) How do you access web storage?

Answer: Web Applications can store data on the web browser. Web storage is more secure, and through this, we can keep a large amount of data locally without rendering the web application’s performance. We can access web storage using local-storage objects that have no expiration date in contrast to session storage. 

We can access the web storage using : 

myStorage = window.localStorage;

Question 18)What are the different tools and techniques used for debugging Javascript code?

Answer: The best ten debugger tools of javascript are :

  1. Firefox Javascript debugger 
  2. Google Chrome dev tools
  3. Opera Chromium Dev tools 
  4. Safari Developer Menu
  5. Flow
  6. Omnibug
  7. SplineTech Javascript Debugger
  8. Raygun error monitoring 
  9. JS Bin 
  10. Edge Javascript Debugger

Question 19)What is JSON?

Answer: Javascript Object Notation is a text-based representation of structured data which is based on critical values and ordered lists. JSON is derived from Javascript and is now found everywhere on the web. It has not become the format of choice for almost every public web service on the Internet.

Question 20) What will be the output on the console and why?

const student = {
  age: 20,
  name: 'Coding Ninjas'
};

const classroom = [student, student, student];
classroom[1].name = 'Coding';
console.log(classroom[0].name);

Answer: The output will be Coding.
In the above code, the classroom references are pointed onto the same memory space ‘student’. 

Any change in either of the references would result in a change in all the other references too.

Question 21)What is the difference between the ‘~’ and the ‘^’ in the semver syntax, such as that used in the npm package.json file?

Answer: npm uses ~ and ^ to designate which patch and the minor version is to be used. Semver syntax goes as follows: major.minor.patch.

 The ‘~’, such as “lodash”: “~1.2.0”, will only update the patch version. The ‘^’, such as “lodash”: “^1.2.0”, will update the minor and patch version.

Question 22) What are the limitations of using strict mode in Javascript?

Answer: The limitations of using strict mode are:

  1. We cannot use reserved words as variable names.
  2. We will have to declare all the variables, as the compiler won’t declare them in strict mode.
  3. Deleting undeleted properties would throw an error.

Question 23) What is an Event Delegation?

Answer: Event Delegation allows users to append a single event listener to a parent element that adds it to all of its present and future descendants that match a selector.

The main steps involve:

  1. Add a handler on a container
  2. Add the event.target source element on the handler
  3. Handle the event

For example, if we want to detect field changes in forms, we can use event delegation.

var formfile = document.querySelector('#registrationform');

// Listen for changes to fields inside the form
formfile.addEventListener('input', function (event) {

// Log the field that was changed
console.log(event.target);

}, false);

Question 24) What is Template Strings in JS?

Answer: Template strings or literals in javascript are literals that are delimited with backticks, allowing embedded expressions called substitutions. Template Literals are sometimes called template strings but they are not String Literals and cannot be used in the same way. Tagged Template Literals sometimes do not even result in a string, the final outcome depends on the tag function.

// Untagged, these create strings:
`string text`

`string text line 1
string text line 2`

`string text ${expression} string text`

// Tagged, this calls the function "example" with the template as the
// first argument and substitution values as subsequent arguments:
example`string text ${expression} string text`

Question 25)What is the use of the clearInterval Method?

Answer: The clearinterval method is used to clear any intervals that were set using setinterval.The return value returned by setInterval() function is stored in a variable and it’s passed into the clearInterval() function to clear the interval.

For example, the below code is used to display the message after every 4 seconds and this can be cleared by using clearinterval.

<script>
var msg;
function greeting() {
  alert('Codingninjas');
}
function start() {
  msg = setInterval(greeting, 4000);

}

function stop() {
    clearInterval(msg);
}
</script>

Question 26)How can we validate an email in Javascript?

Answer: Email validation is a critical part of validating an HTML form. An email is a string or a subset of ASCII characters separated into two parts by @ symbol. The first part contains personal information while the other contains the domain name at which the email is registered.We can validate an email in Javascript using regular expressions. 

It is always recommended to do server side validation as javascript can be disabled on the client side.

For example,

function validateEmail(email) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(String(email).toLowerCase());
}

Question 27) What are the different types of errors available in Javascript?

Answer: There are mainly three types of errors in Javascript :

  1. Logical Errors: This type of error comes when there is a logical error in the code.
  2. Load time Error: This type of error occurs due to a syntactical mistake or when a resource is unavailable for allocation.
  3. Run-Time Errors: These errors occur due to a command inside the HTML or any unexpected conditional scenario.

Question 28)What is a conditional operator in Javascript?

Answer: The javascript’s conditional (ternary) operator uses three operands as a shortcut for the if statement.

The three operands are :

  1. A condition followed by a question mark
  2. Expression to execute if the statement is true, followed by a colon
  3. Another expression is to be executed if the condition is false.

For example,

var age = 18;
var vote = (age >= 18) ? "Yes" : "No";
console.log(vote); // "Yes"
//a small program to check if a user can vote or not.
Output:
Yes

Question 29)What are regular expression patterns 

Answer: Regular Expressions provide a group of patterns to match characters.

They are categorized into three types, 

  1. Brackets: These are used to find a range of characters. For example, below are some use cases, [abc]: Used to find any of the characters between the brackets(a,b,c) [0-9]: Used to find any of the digits between the brackets (a|b): Used to find any of the alternatives separated with | 
  1. Metacharacters: These are characters that have a special meaning. For example, below are some use cases, ‘\d’: It is used to find a digit ‘\s’: It is used to find a whitespace character ‘\b’: It is used to find a match either at the beginning or end of a word
  1. Quantifiers: They are used to define different quantities. For example, here are some of the use cases, n+: Used to find matches for any string that contains at least one.

Question 30)What is the output of the below code : 

function delay() {
  return new Promise(resolve => setTimeout(resolve, 2000));
}

async function delayedLog(item) {
  await delay();
  console.log(item);
}

async function processArray(array) {
  array.forEach(item => {
    await delayedLog(item);
  })
}

processArray([1, 2, 3, 4]);

Answer: We will get a syntax error because, even though processArray is an async function, the for-each loop is placed inside a synchronous function.

As the program awaits inside the synchronous function, an error is thrown.

Key Takeaways

This article discussed the intermediate-level Javascript interview questions every developer should know for a Javascript Interview.
The article covered the most heated topics in Javascript.