JavaScript Interview Questions Part 3

What is babel

“Babel is a JavaScript transpiler to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Some of the main features are listed below,

Transform syntax
Poly fill features that are missing in your target environment (using @babel/polyfill)
Source code transformations (or code mods)”

How do you detect primitive or non primitive value type

“In JavaScript, primitive types include Boolean, string, number, BigInt, null, Symbol and undefined. Whereas non-primitive types include the Objects. But you can easily identify them with the below function,

var myPrimitive = 30;
var myNonPrimitive = {};
function isPrimitive(val) {
return Object(val) !== val;
}

isPrimitive(myPrimitive);
isPrimitive(myNonPrimitive);
If the value is a primitive data type, the Object constructor creates a new wrapper object for the value. But If the value is a non-primitive data type (an object), the Object constructor will give the same object.”

What is the difference between shim and poly fill

A shim is a library that brings a new API to an older environment, using only the means of that environment. It isn’t necessarily restricted to a web application. For example, es5-shim.js is used to emulate ES5 features on older browsers (mainly pre IE9). Whereas poly fill is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively. In a simple sentence, A poly fill is a shim for a browser API.

JavaScript Interview Questions

What is a micro Task queue

Microtask Queue is the new queue where all the tasks initiated by promise objects get processed before the callback queue. The microtasks queue are processed before the next rendering and painting jobs. But if these microtasks are running for a long time then it leads to visual degradation.

How do you use JavaScript libraries in typescript file

“It is known that not all JavaScript libraries or frameworks have TypeScript declaration files. But if you still want to use libraries or frameworks in our TypeScript files without getting compilation errors, the only solution is declare keyword along with a variable declaration. For example, let’s imagine you have a library called custom Library that doesn’t have a TypeScript declaration and have a namespace called custom Library in the global namespace. You can use this library in typescript code as below,

declare var custom Library;
In the runtime, typescript will provide the type to the custom Library variable as any type. The another alternative without using declare keyword is below

var custom Library: any;”

What are tasks in event loop

“A task is any java script code/program which is scheduled to be run by the standard mechanisms such as initially starting to run a program, run an event callback, or an interval or timeout being fired. All these tasks are scheduled on a task queue. Below are the list of use cases to add tasks to the task queue,

When a new java script program is executed directly from console or running by the

Advance JavaScript Interview Questions

How do you implement zero timeout in modern browsers

You can’t use set Timeout(fn, 0) to execute the code immediately due to minimum delay of greater than 0ms. But you can use window.postMessage() to achieve this behavior.

What is minimum timeout throttling

“Both browser and NodeJS JavaScript environments throttles with a minimum delay that is greater than 0ms. That means even though setting a delay of 0ms will not happen instantaneously. Browsers: They have a minimum delay of 4ms. This throttle occurs when successive calls are triggered due to callback nesting(certain depth) or after a certain number of successive intervals. Note: The older browsers have a minimum delay of 10ms. Nodejs: They have a minimum delay of 1ms. This throttle happens when the delay is larger than 2147483647 or less than 1. The best example to explain this timeout throttling behavior is the order of below code snippet.

function runMeFirst() {
console.log(‘My script is initialized’);
}
setTimeout(runMeFirst, 0);
console.log(‘Script loaded’);
and the output would be in

Script loaded
My script is initialized
If you don’t use setTimeout, the order of logs will be sequential.

function runMeFirst() {
console.log(‘My script is initialized’);
}
runMeFirst();
console.log(‘Script loaded’);
and the output is,

My script is initialized
Script loaded”

What is web speech API

“Web speech API is used to enable modern browsers recognize and synthesize speech(i.e, voice data into web apps). This API has been introduced by W3C Community in the year 2012. It has two main parts,

Speech Recognition (Asynchronous Speech Recognition or Speech-to-Text): It provides the ability to recognize voice context from an audio input and respond accordingly. This is accessed by the Speech Recognition interface. The below example shows on how to use this API to get text from speech,
window.SpeechRecognition = window.webkitSpeechRecognition || window.SpeechRecognition; // webkitSpeechRecognition for Chrome and SpeechRecognition for FF
const recognition = new window.SpeechRecognition();
recognition.onresult = (event) => { // SpeechRecognitionEvent type
const speechToText = event.results[0][0].transcript;
console.log(speechToText);
}
recognition.start();
In this API, browser is going to ask you for permission to use your microphone

SpeechSynthesis (Text-to-Speech): It provides the ability to recognize voice context from an audio input and respond. This is accessed by the SpeechSynthesis interface. For example, the below code is used to get voice/speech from text,
if(‘speechSynthesis’ in window){
var speech = new SpeechSynthesisUtterance(‘Hello World!’);
speech.lang = ‘en-US’;
window.speechSynthesis.speak(speech);
}”

JavaScript Interview Questions

How to cancel a fetch request

“Until a few days back, One shortcoming of native promises is no direct way to cancel a fetch request. But the new Abort Controller from js specification allows you to use a signal to abort one or multiple fetch calls. The basic flow of cancelling a fetch request would be as below,

Create an AbortController instance
Get the signal property of an instance and pass the signal as a fetch option for signal
Call the AbortController’s abort property to cancel all fetches that use that signal For example, let’s pass the same signal to multiple fetch calls will cancel all requests with that signal,
const controller = new AbortController();
const { signal } = controller;

fetch(“”http://localhost:8000″”, { signal }).then(response => {
console.log(Request 1 is complete!);
}).catch(e => {
if(e.name === “”AbortError””) {
// We know it’s been canceled!
}
});

fetch(“”http://localhost:8000″”, { signal }).then(response => {
console.log(Request 2 is complete!);
}).catch(e => {
if(e.name === “”AbortError””) {
// We know it’s been canceled!
}
});

// Wait 2 seconds to abort both requests
setTimeout(() => controller.abort(), 2000);”

What are the different ways to deal with Asynchronous Code

“Below are the list of different ways to deal with Asynchronous code.

Callbacks
Promises
Async/await
Third-party libraries such as async.js,bluebird etc”

What are wrapper objects

“Primitive Values like string,number and Boolean don’t have properties and methods but they are temporarily converted or coerced to an object(Wrapper object) when you try to perform actions on them. For example, if you apply toUpperCase() method on a primitive string value, it does not throw an error but returns uppercase of the string.

let name = “”john””;

console.log(name.toUpperCase()); // Behind the scenes treated as console.log(new String(name).toUpperCase());
i.e, Every primitive except null and undefined have Wrapper Objects and the list of wrapper objects are String,Number,Boolean,Symbol and BigInt.”

Advance JavaScript Interview Questions

How do you capture browser back button

“The window.onbeforeunload method is used to capture browser back button events. This is helpful to warn users about losing the current data.

window.onbeforeunload = function() {
alert(“”You work will be lost””);
};

What is the easiest multi condition checking

“You can use index Of to compare input with multiple values instead of checking each value as one condition.

// Verbose approach
if (input === ‘first’ || input === 1 || input === ‘second’ || input === 2) {
someFunction();
}
// Shortcut
if ([‘first’, 1, ‘second’, 2].indexOf(input) !== -1) {
someFunction();
}
⬆ Back to “

How do you flattening multi dimensional arrays

“Flattening bi-dimensional arrays is trivial with Spread operator.

const biDimensionalArr = [11, [22, 33], [44, 55], [66, 77], 88, 99];
const flattenArr = [].concat(…biDimensionalArr); // [11, 22, 33, 44, 55, 66, 77, 88, 99]
But you can make it work with multi-dimensional arrays by recursive calls,

function flattenMultiArray(arr) {
const flattened = [].concat(…arr);
return flattened.some(item => Array.isArray(item)) ? flattenMultiArray(flattened) : flattened;
}
const multiDimensionalArr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]];
const flatArr = flattenMultiArray(multiDimensionalArr); // [11, 22, 33, 44, 55, 66, 77, 88, 99]”

JavaScript Interview Questions

What is the shortcut to get timestamp

“You can use new Date().getTime() to get the current timestamp. There is an alternative shortcut to get the value.

console.log(+new Date());
console.log(Date.now());”

How do you create copy to clipboard button

“You need to select the content(using .select() method) of the input element and execute the copy command with execCommand (i.e, execCommand(‘copy’)). You can also execute other system commands like cut and paste.

document.querySelector(“”#copy-button””).onclick = function() {
// Select the content
document.querySelector(“”#copy-input””).select();
// Copy to the clipboard
document.execCommand(‘copy’);
};”

How do you verify that an argument is a Number or not

“The combination of IsNaN and isFinite methods are used to confirm whether an argument is a number or not.

function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}”

Advance JavaScript Interview Questions

How do you create an array with some data

“You can create an array with some data or an array with the same values using fill method.

var newArray = new Array(5).fill(“”0″”);
console.log(newArray); // [“”0″”, “”0″”, “”0″”, “”0″”, “”0″”]”

Define anonymous function

“It is a function that has no name. These functions are declared dynamically at runtime using the function operator instead of the function declaration. The function operator is more flexible than a function declaration. It can be easily used in the place of an expression. For example:

var display=function()
{
alert(“”Anonymous Function is invoked””);
}
display(); “

What are the options in a cookie

“There are few below options available for a cookie,

By default, the cookie is deleted when the browser is closed but you can change this behavior by setting expiry date (in UTC time).
document.cookie = “”username=John; expires=Sat, 8 Jun 2019 12:00:00 UTC””;
By default, the cookie belongs to a current page. But you can tell the browser what path the cookie belongs to using a path parameter.
document.cookie = “”username=John; path=/services””;”

JavaScript Interview Questions

How do you delete a cookie

“You can delete a cookie by setting the expiry date as a passed date. You don’t need to specify a cookie value in this case. For example, you can delete a username cookie in the current page as below.

document.cookie = “”username=; expires=Fri, 07 Jun 2019 00:00:00 UTC; path=/;””;
Note: You should define the cookie path option to ensure that you delete the right cookie. Some browsers doesn’t allow to delete a cookie unless you specify a path parameter.”

What is the main difference between localStorage and sessionStorage

Local Storage is the same as Session Storage but it persists the data even when the browser is closed and reopened (i.e it has no expiration time) whereas in session Storage data gets cleared when the page session ends.

How do you access web storage

“The Window object implements the WindowLocalStorage and WindowSessionStorage objects which has localStorage(window.localStorage) and sessionStorage(window.sessionStorage) properties respectively. These properties create an instance of the Storage object, through which data items can be set, retrieved and removed for a specific domain and storage type (session or local). For example, you can read and write on local storage objects as below

localStorage.setItem(‘logo’, document.getElementById(‘logo’).value);
localStorage.getItem(‘logo’);”

Advance JavaScript Interview Questions

What are the methods available on session storage

“The session storage provided methods for reading, writing and clearing the session data

// Save data to sessionStorage
sessionStorage.setItem(‘key’, ‘value’);

// Get saved data from sessionStorage
let data = sessionStorage.getItem(‘key’);

// Remove saved data from sessionStorage
sessionStorage.removeItem(‘key’);

// Remove all saved data from sessionStorage
sessionStorage.clear();”

What is a storage event and its event handler

“The StorageEvent is an event that fires when a storage area has been changed in the context of another document. Whereas onstorage property is an EventHandler for processing storage events. The syntax would be as below

window.onstorage = functionRef;
Let’s take the example usage of onstorage event handler which logs the storage key and it’s values

window.onstorage = function(e) {
console.log(‘The ‘ + e.key +
‘ key has been changed from ‘ + e.oldValue +
‘ to ‘ + e.newValue + ‘.’);
};”

How do you decode an URL

“The decode URI() function is used to decode a Uniform Resource Identifier (URI) previously created by encode URI().

var uri = ‘https://mozilla.org/?x=шеллы’;
var encoded = encode URI(uri);
console.log(encoded); // https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B
try {
console.log(decodeURI(encoded)); // “”https://mozilla.org/?x=шеллы””
} catch(e) { // catches a malformed URI
console.error(e);
}”

JavaScript Interview Questions

What is the difference between uneval and eval

“The uneval function returns the source of a given object; whereas the eval function does the opposite, by evaluating that source code in a different memory area. Let’s see an example to clarify the difference,

var msg = uneval(function greeting() { return ‘Hello, Good morning’; });
var greeting = eval(msg);
greeting(); // returns “”Hello, Good morning”””

What is the precedence order between local and global variables

“A local variable takes precedence over a global variable with the same name. Let’s see this behavior in an example.

var msg = “”Good morning””;
function greeting() {
msg = “”Good Evening””;
console.log(msg);
}
greeting();”

What is Promise.all

“Promise.all is a promise that takes an array of promises as an input (an iterable), and it gets resolved when all the promises get resolved or any one of them gets rejected. For example, the syntax of Promise.all method is below,

Promise.all([Promise1, Promise2, Promise3]) .then(result) => { console.log(result) }) .catch(error => console.log(Error in promises ${error}))
Note: Remember that the order of the promises(output the result) is maintained as per input order.”

Advance JavaScript Interview Questions

What is a strict mode in JavaScript

Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. This way it prevents certain actions from being taken and throws more exceptions. The literal expression “use strict”; instructs the browser to use the JavaScript code in the Strict mode.

Why do you need strict mode

Strict mode is useful to write “secure” JavaScript by notifying “bad syntax” into real errors. For example, it eliminates accidentally creating a global variable by throwing an error and also throws an error for assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object.

How do you declare strict mode

“The strict mode is declared by adding “”use strict””; to the beginning of a script or a function. If declared at the beginning of a script, it has global scope.

“”use strict””;
x = 3.14; // This will cause an error because x is not declared
and if you declare inside a function, it has local scope

x = 3.14; // This will not cause an error.
myFunction();

function myFunction() {
“”use strict””;
y = 3.14; // This will cause an error
}”

JavaScript Interview Questions

What is the purpose of double exclamation

“The double exclamation or negation(!!) ensures the resulting type is a boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, true. For example, you can test IE version using this expression as below,

let isIE8 = false;
isIE8 = !! navigator.userAgent.match(/MSIE 8.0/);
console.log(isIE8); // returns true or false
If you don’t use this expression then it returns the original value.

console.log(navigator.userAgent.match(/MSIE 8.0/)); // returns either an Array or null
Note: The expression !! is not an operator, but it is just twice of ! operator.”

What is the purpose of the delete operator

“The delete keyword is used to delete the property as well as its value.

var user= {name: “”John””, age:20};
delete user.age;

console.log(user); // {name: “”John””}”

What is the type of operator

“You can use the JavaScript type of operator to find the type of a JavaScript variable. It returns the type of a variable or an expression.

typeof “”John Abraham”” // Returns “”string””
typeof (1 + 2) // Returns “”number”””

Advance JavaScript Interview Questions

What is undefined property

“The undefined property indicates that a variable has not been assigned a value, or not declared at all. The type of undefined value is undefined too.

var user; // Value is undefined, type is undefined
console.log(typeof(user)) //undefined
Any variable can be emptied by setting the value to undefined.

user = undefined”

What is null value

“The value null represents the intentional absence of any object value. It is one of JavaScript’s primitive values. The type of null value is object. You can empty the variable by setting the value to null.

var user = null;
console.log(typeof(user)) //object”

What is eval

“The eval() function evaluates JavaScript code represented as a string. The string can be a JavaScript expression, variable, statement, or sequence of statements.

console.log(eval(‘1 + 2’)); // 3″

JavaScript Interview Questions

How do you access history in JavaScript

“The window.history object contains the browser’s history. You can load previous and next URLs in the history using back() and next() methods.

function goBack() {
window.history.back()
}
function goForward() {
window.history.forward()
}
Note: You can also access history without window prefix.”

How do you detect caps lock key turned on or not

“he mouse Event getModifierState() is used to return a Boolean value that indicates whether the specified modifier key is activated or not. The modifiers such as Caps Lock, Scroll Lock and NUM Lock are activated when they are clicked, and deactivated when they are clicked again.

Let’s take an input element to detect the Caps Lock on/off behavior with an example,

<input type=""password"" onmousedown=""enterInput(event)"">

<p id=""feedback""></p>

<script>
function enterInput(e) {
  var flag = e.getModifierState(""CapsLock"");
  if(flag) {
      document.getElementById(""feedback"").innerHTML = ""CapsLock activated"";

  } else {
      document.getElementById(""feedback"").innerHTML = ""CapsLock not activated"";
  }
}
</script>"

What are global variables

“Global variables are those that are available throughout the length of the code without any scope. The var keyword is used to declare a local variable but if you omit it then it will become global variable

msg = “”Hello”” // var is missing, it becomes global variable”

Advance JavaScript Interview Questions

What are the problems with global variables

The problem with global variables is the conflict of variable names of local and global scope. It is also difficult to debug and test the code that relies on global variables.

What is the purpose of is Finite function

“The is Finite() function is used to determine whether a number is a finite, legal number. It returns false if the value is +infinity, -infinity, or Nan (Not-a-Number), otherwise it returns true.

isFinite(Infinity); // false
isFinite(NaN); // false
isFinite(-Infinity); // false

isFinite(100); // true”

What is an event flow

“Event flow is the order in which event is received on the web page. When you click an element that is nested in various other elements, before your click actually reaches its destination, or target element, it must trigger the click event for each of its parent elements first, starting at the top with the global window object. There are two ways of event flow

Top to Bottom(Event Capturing)
Bottom to Top (Event Bubbling)”

JavaScript Interview Questions

What is event capturing

Event capturing is a type of event propagation where the event is first captured by the outermost element, and then successively triggers on the descendants (children) of the target element in the same nesting hierarchy till it reaches the innermost DOM element.

JavaScript Part 1JavaScript Part 2
Back to top