Question 376
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);
}
Question 376
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);
}
Question 377
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");
};
Question 378
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());
Question 379
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]
Also you can use the flat method of Array.
const arr = [1, [2, 3], 4, 5, [6, 7]];
const fllattenArr = arr.flat(); // [1, 2, 3, 4, 5, 6, 7]
// And for multiDimensional arrays
const multiDimensionalArr = [
11,
[22, 33],
[44, [55, 66, [77, [88]], 99]],
];
const oneStepFlat = multiDimensionalArr.flat(1); // [11, 22, 33, 44, [55, 66, [77, [88]], 99]]
const towStep = multiDimensionalArr.flat(2); // [11, 22, 33, 44, 55, 66, [77, [88]], 99]
const fullyFlatArray = multiDimensionalArr.flat(Infinity); // [11, 22, 33, 44, 55, 66, 77, 88, 99]
Question 380
You can use indexOf 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();
}
Question 381
The beforeunload event is triggered when the window, the document and its resources are about to be unloaded. This event is helpful to warn users about losing the current data and detect back button event.
window.addEventListener("beforeunload", () => {
console.log("Clicked browser back button");
});
You can also use popstate event to detect the browser back button.
Note: The history entry has been activated using history.pushState method.
window.addEventListener("popstate", () => {
console.log("Clicked browser back button");
box.style.backgroundColor = "white";
});
const box = document.getElementById("div");
box.addEventListener("click", () => {
box.style.backgroundColor = "blue";
window.history.pushState({}, null, null);
});
In the preceeding code, When the box element clicked, its background color appears in blue color and changed to while color upon clicking the browser back button using popstate event handler. The state property of popstate contains the copy of history entry's state object.
Question 382
The right click on the page can be disabled by returning false from the oncontextmenu attribute on the body element.
<body oncontextmenu="return false;"></body>
Question 383
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.
Question 384
AJAX stands for Asynchronous JavaScript and XML and it is a group of related technologies(HTML, CSS, JavaScript, XMLHttpRequest API etc) used to display data asynchronously. i.e. We can send data to the server and get data from the server without reloading the web page.
Question 385
Below are the list of different ways to deal with Asynchronous code.
Question 386
Until a few days back, One shortcoming of native promises is no direct way to cancel a fetch request. But the new AbortController 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,
AbortController instanceconst 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);
Question 387
Web speech API is used to enable modern browsers recognize and synthesize speech(i.e, voice data into web apps). This API was introduced by W3C Community in the year 2012. It has two main parts:
SpeechRecognition interface.
The example below shows 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 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);
}
The above examples can be tested on chrome(33+) browser's developer console. Note: This API is still a working draft and only available in Chrome and Firefox browsers(ofcourse Chrome only implemented the specification)
Question 388
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
Question 389
You can't use setTimeout(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.
Question 390
A task is any javascript 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,
<script> element, the task will be added to the task queue.