JavaScript Web APIs are built-in browser features that allow JavaScript to interact with the browser, system hardware, and external services. They are not part of core JavaScript, but are provided by the browser environment to extend JavaScript’s capabilities.
Web APIs allow you to:
Without Web APIs, JavaScript would be limited to basic logic only.
This is why Web APIs often work asynchronously.
The Fetch API is used to make HTTP requests (GET, POST, etc.).
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Used for:
Stores data permanently in the browser.
localStorage.setItem("username", "Learn2Kode");
let name = localStorage.getItem("username");
Stores data for the current session only.
sessionStorage.setItem("token", "12345");
Used to get the user’s location (with permission).
navigator.geolocation.getCurrentPosition(position => {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
});
The DOM itself is a Web API that allows JavaScript to manipulate HTML.
document.getElementById("title").textContent = "Hello Web APIs";
Provided by the browser for delays and intervals.
setTimeout(() => {
console.log("Executed after 2 seconds");
}, 2000);
| Feature | Core JavaScript | Web APIs |
|---|---|---|
| Provided by | ECMAScript | Browser |
| Examples | Variables, loops | Fetch, DOM, Storage |
| Async support | Limited | Strong |
Use Web APIs when you need to: