JavaScript Interview Questions 31-35 (Storage, AJAX, JSON, API Patterns)
Welcome to the final set of our JavaScript interview series. In this section, we move away from syntax and theory into practical scenarios you will face daily: storing data in the user's browser and managing complex communication with servers.
We will cover the differences between storage options (Cookies, Local, and Session), explain the format of the web (JSON), and tackle two very common coding interview scenarios: handling API calls one after another, and handling them all at the same time.
31. What is the difference between cookies, localStorage, and sessionStorage?
All three are ways to store data on the client's browser, but they differ in capacity, lifetime, and how they interact with the server.
| Feature | Cookies | localStorage | sessionStorage |
|---|---|---|---|
| Capacity | Small (~4KB) | Large (~5-10MB) | Large (~5-10MB) |
| Expiration | Manually set or Session | Never (until deleted) | When tab closes |
| Server Access | Sent with every HTTP request | Client-side only | Client-side only |
Analogy:
Cookie: Like an ID badge in your pocket. You show it automatically every time you walk through a door (server request).
localStorage: Like a notebook in your desk drawer. You write things down, and they stay there forever, even if you leave and come back next week.
sessionStorage: Like a whiteboard in a meeting room. It is useful while you are there, but the moment the meeting ends (you close the tab), it gets wiped clean.
// 1. localStorage (Persistent)
localStorage.setItem("theme", "dark");
console.log(localStorage.getItem("theme")); // "dark"
// 2. sessionStorage (Temporary)
sessionStorage.setItem("draftParams", "user=123");
// 3. Cookies (Old school, manual string manipulation)
document.cookie = "username=JohnDoe; expires=Thu, 18 Dec 2025 12:00:00 UTC";
32. What is AJAX in JavaScript?
AJAX stands for Asynchronous JavaScript and XML. It is not a programming language itself, but a technique used to update parts of a web page without reloading the whole page.
Historically, it used XML to transport data, but nowadays, it almost exclusively uses JSON. It enables the rich, fast "app-like" feel of modern websites.
Analogy: Imagine you are watching a movie on TV. You get hungry.
Without AJAX (Old Web): To order pizza, you have to turn off the TV, drive to the store, buy the pizza, drive back, and restart the movie. (Page Reload).
With AJAX (Modern Web): You pick up your phone and order the pizza. The movie keeps playing. The pizza arrives at your door in the background, and you eat it while the movie continues. (Asynchronous Update).
33. What is JSON and how is it used in JavaScript?
JSON stands for JavaScript Object Notation. It is a lightweight text-based format for storing and transporting data. While it looks exactly like a JavaScript object, it is actually a string.
Two critical methods allow JavaScript to interact with JSON:
- JSON.stringify(): Converts a JavaScript object into a JSON string (for sending to a server).
- JSON.parse(): Converts a JSON string into a JavaScript object (for using data received from a server).
const user = {
name: "Alice",
age: 25,
isAdmin: true
};
// 1. Convert Object to String (Sending data)
const jsonString = JSON.stringify(user);
console.log(typeof jsonString); // string
console.log(jsonString); // '{"name":"Alice","age":25,"isAdmin":true}'
// 2. Convert String to Object (Receiving data)
const receivedData = '{"name":"Bob","age":30}';
const userObj = JSON.parse(receivedData);
console.log(userObj.name); // Bob
Sample Output:
string
{"name":"Alice","age":25,"isAdmin":true}
Bob
34. Scenario: How do you make sequential API calls in JavaScript?
The Problem: You need to make API Call B, but it depends on data returned from API Call A. (e.g., Fetch a User ID, then use that ID to fetch their Posts).
The Solution: Use async/await. By "awaiting" the first call, you pause the function until the data arrives, then proceed to the second call.
// Mock API function that returns a promise
const fetchFromAPI = (msg, time) =>
new Promise(resolve => setTimeout(() => resolve(msg), time));
async function sequentialCalls() {
console.log("1. Starting...");
// Wait for User Data
const user = await fetchFromAPI("User Data Loaded", 1000);
console.log(user);
// Wait for Posts (using info from user)
const posts = await fetchFromAPI("User Posts Loaded", 1000);
console.log(posts);
console.log("3. All Done!");
}
sequentialCalls();
Sample Output:
1. Starting...
// (Wait 1s)
User Data Loaded
// (Wait 1s)
User Posts Loaded
3. All Done!
// Total time: ~2 seconds
35. Scenario: How do you handle multiple API calls in parallel?
The Problem: You need to fetch Users, Products, and Settings to load a dashboard. None of them depend on each other. Fetching them one by one (sequentially) is too slow.
The Solution: Use Promise.all(). It accepts an array of promises and runs them simultaneously. It waits for theslowest one to finish and then returns an array of results.
Note: If any promise in the array fails, Promise.all will fail immediately. For more resilience, you might look into Promise.allSettled().
const fetchFromAPI = (msg, time) =>
new Promise(resolve => setTimeout(() => resolve(msg), time));
async function parallelCalls() {
console.log("1. Starting all requests...");
// Trigger all 3 at once. Do NOT await them individually here.
const p1 = fetchFromAPI("Users", 2000); // Slowest
const p2 = fetchFromAPI("Products", 1000);
const p3 = fetchFromAPI("Settings", 500);
// Wait for all to finish
const results = await Promise.all([p1, p2, p3]);
console.log("2. All Data Arrived:", results);
}
parallelCalls();
Sample Output:
1. Starting all requests...
// (Wait ~2 seconds total, determined by the slowest request)
2. All Data Arrived: [ 'Users', 'Products', 'Settings' ]
Congratulations! You have completed this comprehensive JavaScript interview preparation series. From data types to parallel API orchestration, you now have the vocabulary and the code examples to tackle technical discussions with confidence. Review these patterns, try writing them from scratch, and good luck with your interviews!