JavaScript Web APIs — Interview Questions & Answers
Ques: What are Web APIs in JavaScript?
Ans: Web APIs are browser-provided interfaces that allow developers to interact with various browser and system features like storage, network, location, and clipboard.
They extend JavaScript’s power beyond the webpage DOM.
Examples:
localStorage(Storage API)fetch()(Fetch API)navigator.geolocation(Geolocation API)navigator.clipboard(Clipboard API)Worker(Web Workers)
Ques: What is the difference between JavaScript Core APIs and Web APIs?
| Type | Description | Example |
|---|---|---|
| Core JS APIs | Built into JS language | Math, Date, Array, Promise |
| Web APIs | Provided by browser (not part of core JS) | fetch, localStorage, navigator |
Ques: What is the Form Validation API in JavaScript?
Ans: The Form Validation API helps validate form input fields without writing complex JavaScript code.
Common methods & properties:
checkValidity()– returnstrueif form/input is validsetCustomValidity()– sets a custom messagereportValidity()– shows browser validation UI
Example:
let form = document.querySelector("form");
if (!form.checkValidity()) {
form.reportValidity();
}
Ques: How do you check if a specific input field is valid?
let email = document.getElementById("email");
if (email.validity.typeMismatch) {
email.setCustomValidity("Please enter a valid email address!");
}
Ques: What is the Storage API in JavaScript?
Ans: The Storage API allows storing key–value data directly in the browser.
It includes:
- localStorage → Persistent storage (no expiry)
- sessionStorage → Data cleared when tab closes
Ques: What is the difference between localStorage and sessionStorage?
| Feature | localStorage | sessionStorage |
|---|---|---|
| Lifetime | Permanent (until cleared) | Removed when tab closes |
| Scope | Shared across tabs | Per tab/session |
| Size Limit | ~5–10 MB | ~5 MB |
| Example | Save user preferences | Temporary data during form fill |
Ques: How to store and retrieve data in localStorage?
localStorage.setItem("username", "John");
console.log(localStorage.getItem("username")); // John
Ques: How to remove or clear data from localStorage?
localStorage.removeItem("username"); // remove specific
localStorage.clear(); // remove all
Ques: What is the Worker API in JavaScript?
Ans: The Worker API allows running JavaScript code in background threads, separate from the main UI thread.
It helps improve performance for heavy computations.
Ques: What is a Web Worker?
Ans: A Web Worker runs scripts in the background, so the webpage remains responsive.
Example:
// worker.js
self.onmessage = (e) => {
self.postMessage(e.data * 2);
};
// main.js
let worker = new Worker("worker.js");
worker.postMessage(5);
worker.onmessage = (e) => console.log(e.data); // 10
Ques: Can Web Workers access the DOM directly?
Ans: No, Web Workers cannot access the DOM or window object.
They can only communicate with the main thread using postMessage() and onmessage.
Ques: What is the Fetch API?
Ans: The Fetch API is used to make HTTP requests.
It returns a Promise, simplifying asynchronous data fetching.
Example:
fetch("<https://api.example.com/data>")
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
Ques: What is the advantage of using Fetch over XMLHttpRequest (XHR)?
| Feature | Fetch API | XMLHttpRequest |
|---|---|---|
| Syntax | Promise-based | Callback-based |
| Simplicity | Cleaner & modern | Verbose |
| Streaming | Supported | Limited |
| Async/Await | Easily supported | Not native |
Ques: How can you handle errors in Fetch?
fetch("invalid-url")
.then(res => {
if (!res.ok) throw new Error("Network error");
return res.json();
})
.catch(err => console.error(err.message));
Ques: How do Promise.all(), Promise.race(), and Promise.any() work with Fetch API?
Promise.all()→ Waits for all Promises to resolvePromise.race()→ Returns the first settled PromisePromise.any()→ Returns first fulfilled Promise
Example:
Promise.all([
fetch("/api/1"),
fetch("/api/2")
]).then(res => console.log("All done!"));
Ques: What is the Geolocation API?
Ans: The Geolocation API lets you access the user’s physical location (with permission).
Example:
navigator.geolocation.getCurrentPosition(
pos => console.log(pos.coords.latitude, pos.coords.longitude),
err => console.error(err)
);
Ques: How can you continuously track location changes?
let watchId = navigator.geolocation.watchPosition(
pos => console.log(pos.coords.latitude, pos.coords.longitude)
);
navigator.geolocation.clearWatch(watchId); // stop tracking
Ques: What are common errors in Geolocation API?
- User denied permission
- Position unavailable
- Timeout error
- Browser doesn’t support Geolocation
Check support:
if ("geolocation" in navigator) {
console.log("Supported");
}
Ques: What is the Clipboard API?
Ans: The Clipboard API provides access to the system clipboard for reading/writing text (with permission).
Ques: How do you copy text to the clipboard?
navigator.clipboard.writeText("Hello World!")
.then(() => alert("Copied!"))
.catch(err => console.error("Failed:", err));
Ques: How do you read text from the clipboard?
navigator.clipboard.readText()
.then(text => console.log("Pasted:", text));
Ques: What are the permissions required for Clipboard API?
Ans: Clipboard API usually requires:
- HTTPS connection
- User gesture (e.g., button click)
Ques: What is the difference between synchronous and asynchronous APIs?
| Type | Description | Example |
|---|---|---|
| Synchronous | Executes line by line, blocking next operation | localStorage.getItem() |
| Asynchronous | Doesn’t block next operation, uses callbacks or Promises | fetch(), navigator.geolocation.getCurrentPosition() |
Ques: What are some commonly used Web APIs in modern web apps?
- Storage API – Save user data locally
- Fetch API – Communicate with servers
- Web Workers – Background tasks
- Geolocation API – Track user location
- Clipboard API – Copy/paste functionality
- Web Speech API – Speech recognition and synthesis
- Notifications API – Browser notifications
Ques: What are the advantages of Web APIs?
- Access powerful browser features
- Enable asynchronous operations
- Improve UX (e.g., geolocation, clipboard)
- Reduce dependency on third-party libraries
- Increase app performance and responsiveness
