71. What is fetch()?
fetch() is a modern JavaScript API used to make HTTP requests and communicate with servers.It returns a Promise.
Example:
fetch("https://api.example.com/users")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});Using async/await:
async function getUsers() {
try {
const response = await fetch(
"https://api.example.com/users"
);
const data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}Interview Tip:
fetch() rejects its Promise for network-level failures, but an HTTP error such as 404 or 500 does not automatically reject it. You should check response.ok.72. What is AJAX?
AJAX stands for Asynchronous JavaScript and XML.
It is a technique for communicating with a server and updating parts of a webpage without reloading the entire page.
Despite the name, AJAX doesn't require XML. Modern applications commonly exchange JSON.
Example:
A webpage can request:
User data โ Server
โ
JSON
โ
JavaScript
โ
Update webpage
Modern Approach:
Today,
fetch() is commonly used instead of the older XMLHttpRequest API.73. What are Web APIs?
Web APIs are browser-provided interfaces that allow JavaScript to interact with browser features and the environment.
Examples include:
โข
fetch()โข
setTimeout()โข DOM APIs
โข Local Storage
โข Geolocation API
โข Web Workers
โข Clipboard API
Example:
setTimeout(() => {
console.log("Hello");
}, 1000);The timer functionality is provided by the host environment, such as a browser or Node.js runtime, rather than being part of the JavaScript language itself.
Interview Tip:
Don't confuse JavaScript language features with browser Web APIs.
74. What is setTimeout()?
setTimeout() schedules a function to run after a specified delay.Example:
setTimeout(() => {
console.log("Hello");
}, 2000);The callback becomes eligible to run after approximately 2 seconds.
Important:
The delay is not a guarantee that the function executes exactly at that time.
It may execute later if the JavaScript runtime is busy.
75. What is setInterval()?
setInterval() repeatedly schedules a function at approximately specified intervals.Example:
const interval = setInterval(() => {
console.log("Running...");
}, 1000);The callback runs approximately every second until the interval is cancelled.
Stop It:
clearInterval(interval);
Common Uses:
โข Timers
โข Polling
โข Repeated UI updates
โข Periodic tasks
76. What is clearTimeout()?
clearTimeout() cancels a timeout that was previously scheduled using setTimeout().Example:
const timer = setTimeout(() => {
console.log("Hello");
}, 5000);
clearTimeout(timer);The callback will not execute because the timeout was cancelled before it became eligible to run.
Common Use:
Useful when you need to cancel a scheduled action.
77. What is clearInterval()?
clearInterval() stops an interval created using setInterval().Example: