30 Javascript Advanced Interview Questions in 2021: Part 3

30 Javascript Advanced Interview Questions in 2021: Part 3
30 Javascript Advanced Interview Questions in 2021: Part 3

Introduction

Javascript was developed by Brenden Eich and is the most popular language in the field of Web Development. The language creates dynamic web pages and adds functionality to the raw HTML and CSS code.
 

The below are the advanced level, Top 30 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 javascript Interview Questions

asked by most of the companies during the interview.

Advanced Javascript Interview Questions

Question 1) What two programming paradigms are essential for javascript developers?

Answer: Javascript is a programming language that supports OOPS and functional programming. It supports the concept of Object-Oriented Programming along with prototypal inheritance.

Question 2) What is prototypal inheritance?

Answer: In Javascript, we have a unique hidden property called [Prototype], which has either a null value or a reference to another object.

When we try to read a missing property of an object, Javascript would automatically inherit the property from the given prototype. This is known as Prototypal Inheritance.

prototypal_inheritance

Let us consider the given an example,

let student = {
  learn: true,
  study() {
  console.log("Studying");
  }
};

let s1 = {
  sleep: true,
  __proto__: student
};

// study is taken from the prototype
s1.study(); // Studying

Question 3)Explain the screen objects in Javascript.

Answer: Screen Objects are a unique property in Js used to read the information from the user’s screen. Few of the properties of screen objects are

  1. Width: It returns the width of the screen 
  2. Height: It returns the size of the screen
  3. ColorDepth: It returns the color depth of the screen.
  4.  PixelDepth: It returns the pixel depth of the screen

Question 4)What is an object initializer?

Answer: It is an expression that is used to initialize an object. The syntax is a comma-separated list of zeroes or different pairs of property names and associated values of the object.

For example: 

<body>
<h1>Object initializer in JavaScript</h1>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to initialize an object with object initializer and display it</h3>
<script>
  let result = document.querySelector(".result");
  let button = document.querySelector(".Btn");
  let name = "CN";
  let age = 22;
  let place = "New Delhi";
  const person = { name, age, place };
  BtnEle.addEventListener("click", () => {
      result.innerHTML = "person.name = " + person.name + "<br>";
      result.innerHTML += "person.age = " + person.age + "<br>";
      result.innerHTML += "person.place = " + person.place + "<br>";
  });
</script>
</body>

Question 5) What is MEAN in Javascript?

Answer: MongoDB, ExpressJs, Angular JS, and NodeJS all combined in a stack is popularly known as MEAN Stack. It is the most popular tech stack and is used to create dynamic websites to render both server-side and client-side data.

Famous websites like Youtube, Netflix, Amazon, and eBay are all built using MEAN Stack.

Question 6) How can you load JS and CSS dynamically?

Answer: We can create script tags in the DOM and append them as a child tag to a head tag.

We can create a function in Javascript to do so,

function loadcssjs(filename, filetype) {
  if (filetype == "css") { // External CSS file
      var file = document.createElement("link")
      file.setAttribute("rel", "stylesheet");
      file.setAttribute("type", "text/css");
      file.setAttribute("href", filename);
  } else if (filetype == "js") { // External JavaScript file
      var file = document.createElement('script');
      file.setAttribute("type", "text/javascript");
      file.setAttribute("src", filename);
  }
  if (typeof file != "undefined")
      document.getElementsByTagName("head")[0].appendChild(file)
}

Question 7)What will be the output of the following code?

const circle = {
  radius: 40,
  diameter() {
    return this.radius * 2;
  },
  perimeter: () => 2 * Math.PI * this.radius
};
console.log(circle.diameter());
console.log(circle.perimeter());

Answer: The output will be 80 and NaN.

This is because the diameter is a regular function. In contrast, the perimeter value is an arrow function. ‘this’ keyword of a regular function(i.e, diameter) refers to the surrounding scope, a class(i.e, Shape object). At the same time, this keyword of perimeter function refers to the surrounding scope, a window object. Since there is no radius property on window objects, it returns an undefined value, and the multiple number value returns the NaN value.

Question 8)What is a pure function?

Answer: A function is a pure function when it is free from any side effects and will return the same output, given the same input. The output or return value depends on the input/arguments passed in the function. The condition of a pure function is that it must always return a value.

For example,

// PURE FUNCTION
const puresum = (num1, num2) => {
  return num1 + num2;
};

//it will always returns same result given same inputs
puresum(5, 5);
//10
puresum(5, 5);
//10

//IMPURE FUNCTION
let plsMutateMe = 0;
const impuresum = (num) => {
  return (plsMutateMe += num);
};

//returns different result given same inputs
impuresum(5);
//5
impuresum(5);
//10
console.log(plsMutateMe)
//10 

Question 9)What is the difference between a foreach() loop and map()?

Answer: The key difference between the foreach() loop and the map() is that when we use a map(), we get a new array, and no changes are reflected in the current array. So when you want your answer not to reflect any changes in the array, we use a map() function.

→ foreach() loop:

  1. It iterates through each of the elements in the array.
  2. It executes a callback for each iteration.
  3. It does not return any value.
const arr = [1, 2, 3];
const doubled = arr.forEach((num, index) => {
  // Do something with num and/or index.
});

// doubled = undefined

→ map()

  1. It also iterates through each element in the array.
  2. It maps each element to a new element by calling a function for each element. This results in a new array.
const arr = [1, 2, 3];
const doubled = arr.map(num => {
  return num * 2;
});

// doubled = [2, 4, 6]

Question 10)Explain NEGATIVE_INFINITY in Javascript.

Answer: The number.NEGATIVE_INTEGER value represents the negative integer in Javascript. It is a number that can be derived by dividing a negative number from zero.

It is a non-editable and non-configurable property.

For example,

function checkNum(smallNum) {
  if (smallNum === Number.NEGATIVE_INFINITY) {
    return 'Process number as -Infinity';
  }
  return smallNum;
}

console.log(checkNum(-Number.MAX_VALUE));
// output: -1.7976931348623157e+308

console.log(checkNum(-Number.MAX_VALUE * 2));
// output: "Process number as -Infinity"

Question 11)What is the difference between async() and await() in AJAX?

Answer: When an async() function is called, it returns a Promise. When the async() function returns a value, the Promise will be resolved with the returned value. What async() and await() do is free up the request thread while asynchronous work is done.

An async function can contain an await() expression, which pauses the execution of the async() function and waits for the passed Promise’s resolution, and then resumes the async() function’s execution and returns the resolved value.

function resolve5Seconds(x) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(x);
        }, 5000);
    });
}

async function add1(x) {
    const a = await resolve5Seconds(20);
    const b = await resolve5Seconds(30);
    return x + a + b;
}

add1(10).then(v => {
    console.log(v); // prints 60 after 4 seconds.
});

async function add2(x) {
    const p_a = resolve5Seconds(20);
    const p_b = resolve5Seconds(30);
    return x + await p_a + await p_b;
}

add2(10).then(v => {
    console.log(v); // prints 60 after 2 seconds.
});

Question 12)What is the difference between hashing and encryption?

Answer

EncryptionHashing
It is a process in which simple encoding of text is done. The process is secured as it can be decrypted only by the key that is provided to the sole authorized user.It is a process to convert the data into a hash using some hashing functions, and the converted short data is assumed to be the key of the hash.
Encryption is used to protect your data from cyber crimes and is one of the most effective ways to protect your data.Hashes can be used for a large dataset. It is easier to compare hashes than to compare large data.
Encryption is less secure than hashingHashing is more secure than encryption
There are several encryption systems. A few of them are asymmetric encryption, also known as public-key encryption, symmetric encryption, and hybrid encryption, which are the most common.For example, we can use hashing algorithms like MD5() and SHA() algorithms to verify images that are not tampered with in between data transfer over the internet.

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

var a = 1, b = a = typeof b;
console.log(b);  

Answer: The output would be undefined.This happens because of the associativity rule.

The operators with the same precedence are processed based on the associativity property of the operator.Hence the process goes from Right to left,typeof b is undefined so this will be assigned to a. 

The final output is therefore undefined.

Question 14) How can you modify a URL without reloading the page?

Answer: The window.localtion.url property is used to modify the url but it reloads the page. 

HTML5 introduced the history.pushState() and history.replaceState() methods, which allow you to add and modify history entries, respectively without reloading the page.

 Example: 

window.history.pushState('newpage', 'Heading', '/newpage.html');

Question 15) Write a program to find if the string is a palindrome or not.

Answer

function checkpalindrome(str){
  if (str.toLowerCase() === str.toString().toLowerCase().split('').reverse().join('')) {
    return true;
  } else {
    return false;
  }
}
console.log(checkpalindrome('Mom'));
Output:
true

Question 16)Explain the difference between console.log and console.dir in JS.

Answer: console.log prints the output in an HTML-like interface whereas console.dir prints the output in a JSON type tree interface.

For example :

console.log
console.dir

Question 17) Write a function to reverse a string in Javascript.

Answer: 

function reverseaString(str) {
  var reversed = [];
  for(i = str.length - 1; i >= 0; i--){
    reversed.push(str[i]);
  }
  return reversed.join("");
}
console.log(reverseaString('Coding Ninjas'))
Output:

sajniN gnidoC

Question 18)How can we cache the execution of any function?

Answer: We can use the concept of memoization to cache the execution of a given function.

For example, 

const memoizedAdd = () => {
  let cache = {};
  return (n) => {
    if (n in cache) {
      console.log('Fetch from cache');
      return cache[n];
    }
    else {
      console.log('Calculate result');
      let result = n + 10;
      cache[n] = result;
      return result;
    }
  }
}

Question 19)What is a microtask in JS?

Answer: Microtask is a short javascript code that must be executed immediately after the currently conducting task/microtask is completed. They are blocking in nature. i.e., this will stop the main thread until the microtask queue is empty. 

The main sources of microtasks are Promise. resolve, Promise.reject, MutationObservers, IntersectionObservers etc.

microtask

Question 20) How can we implement moveLeft animation in Js?

Answer: We can use setInterval to place the element to the left position by some pixels every 30ms. Hence, we can see the element moving towards the desired position. 

function moveLeft(element, distance) {
  var left = 0;

  function frame() {
    left++;
    element.style.left = left + 'px';

    if (left == distance)
      clearInterval(time)
  }

  var time = setInterval(frame, 30); // draw every 30ms
}

Question 21)How do we use Javascript libraries in Typescript?

Answer:

We know that not all JavaScript libraries or frameworks have TypeScript declaration files. But if we still want to use libraries or frameworks in our TypeScript files without getting compilation errors, the only solution is to declare keywords along with a variable declaration.

 For example, let’s imagine you have a park called custompark that doesn’t have a TypeScript declaration and has a namespace called custompark in the global namespace. We can use this library in typescript code as below, 

declare var custompark; 

In the runtime, typescript will provide the type to the custompark variable as any type. Another alternative without using declare keyword is below 

var custompark: any;

Question 22)How does Javascript Garbage Collector work?

Answer: Garbage Collection is the process of finding unused or free memory available in the application which is not being used. To find the free memory a few algorithms are run by the garbage collector :

  1. Reference Counting Garbage Collection
  2. Mark and Sweep Algorithm
Garbage_Collection

Question 23) How can you merge two arrays in Javascript?

Answer:

We can use the Concat function to merge the two arrays.

// - Merge 2 arrays
function mergeArrays(arr){
  return arr[0].sort().concat(arr[1].sort());
}

mergeArrays([ ['d', 'a'], ['l', 'z', 'x'] ]);

Question 24) What is an Observable?

Answer: Observable is a function that returns values either synchronously or asynchronously to an observer over some time.

The user can simply call the subscribe() method to receive the value.

Observable

For example,

import { Observable } from 'rxjs';

const observable = new Observable(observer => {
  setTimeout(() => {
    observer.next('Message recieved from a Observable!');
  }, 5000);
});

observable.subscribe(value => console.log(value));

Question 25)What is a Proper Tail Call?

Answer: Proper Tail Call is a technique in which the program or code will not create any new stack frames for recursion when a function call is a tail call.

For example,

function factorial(n, acc = 1) {
  if (n === 0) {
    return acc
  }
  return factorial(n - 1, n * acc)
}

This is a tail-recursive function for calculating the factorial of a number.

Question 26) How can you swap values of two variables using destructuring?

Answer: Destructuring is a useful syntactical way to reduce the lines of code and execute the program faster.

The code to swap two values using destructuring is pretty simple,

let var1 = 10;
let var2 =20;
[var1,var2] = [var2,var1];
console.log(var1);
console.log(var2);
Output:
20
10

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

var array1 = new Array(3);
console.log(array1);

var array2 = [];
array2[2] = 100;
console.log(array2);

var array3 = [,,,];
console.log(array3);

Answer: The latest chrome versions display sparse arrays (they are filled with holes) using this empty x n notation. Whereas the older versions have undefined x n notation. Note: The latest version of FF displays n empty slots notation. Hence the output will be :

[empty × 3], [empty × 2, 100], [empty × 3]

Question 28) Explain the browser console features.

Answer: A console is an object which provides access to the user debugging tools in Javascript.

We have various methods in console like : 

  1. log(): It is used to display the output on the console.
  2. error(): It is used to display an error on the console. This is mainly used for testing the entire code.
  3. warn(): It is used to display a warning to the console.
  4. clear(): It is used to clear the console.
  5. table(): It is used to generate a table in the console.

These are a few of the methods available in the console object.

Question 29) Explain High Order Functions in Javascript.

Answer: A high-order Function in JS is a function that accepts parameters and returns a function. These are treated as first-class citizens in Javascript.

Few examples of high-order functions that are built into the language are : 

Array.prototype.Map,Array.prototype.filter and many more

Let’s say we have an array that contains the birth year of various persons and we want to create another array that contains their age,

We can write a high-order function for the same as :

const birthYear = [1993, 1994, 2008, 1995, 1975];
const ages = birthYear.map(year => 2021 - year);

console.log(ages);
Output:
[ 28, 27, 13, 26, 46 ]

Question 30)What is Type Coercion in Javascript?

Answer: Type Coercion is an implicit conversion of data types such as numbers to strings or vice-versa. Type Coercion is similar to Type Conversion the only difference is that Type Coercion is implicit but the Type Conversion can be either Explicit or Implicit.

const value1 = '12';
const value2 = 34;

let sum = value1 + value2;

console.log(sum);

Here 12 is coerced into a string and the sum of a string and a number is the concatenation of the values, hence the Output is 1234

Output:
1234

Key Takeaways

This article discussed the advanced-level Javascript Interview Questions every developer should know before their Interview.