JavaScript Notes
Master the Browser Object Model (BOM) in JavaScript. Learn window, navigator, location, history, screen objects with real examples, diagrams, and interview Q&A.
The Browser Object Model (BOM) gives JavaScript a way to communicate with the browser itself — not the page content (that's the DOM), but the browser *window*, the URL bar, the navigation history, screen dimensions, and more. Think of the BOM as the remote control for the browser.
💡 Key insight: The BOM is not part of the ECMAScript standard. Each browser implements it, but modern browsers follow closely aligned conventions so behaviour is essentially the same everywhere.
Real World Analogy
Think of the BOM like the dashboard of a car:
window= the car itself (everything is inside it)location= the GPS — tells you where you are and lets you navigatehistory= the trip odometer / back button — your route so farnavigator= the car's spec sheet — what model, what fuel, what capabilitiesscreen= the windshield size — how much you can see
Core BOM Objects
1. window — The Global Object
Every variable, function, and browser built-in is a property of window.
console.log(window.innerWidth); // viewport width in pixels
console.log(window.innerHeight); // viewport height in pixels
console.log(window === globalThis); // true in browsers1440 900 true
Useful window methods:
// Open a new tab
const popup = window.open("https://example.com", "_blank");
// Scroll to top
window.scrollTo({ top: 0, behavior: "smooth" });
// Resize window (limited in modern browsers)
window.resizeTo(800, 600);// popup: Window object reference (or null if blocked) // scrollTo: no return value, smooth scrolls to top // resizeTo: no return value
2. window.location — URL Control
location lets you read and change the current URL programmatically.
console.log(location.href); // full URL
console.log(location.hostname); // "example.com"
console.log(location.pathname); // "/products/shoes"
console.log(location.search); // "?color=red&size=10"
console.log(location.hash); // "#reviews"
console.log(location.protocol); // "https:""https://example.com/products/shoes?color=red&size=10#reviews" "example.com" "/products/shoes" "?color=red&size=10" "#reviews" "https:"
Navigating programmatically:
// Redirect (adds to history)
location.href = "https://example.com/cart";
// Replace (does NOT add to history — no back button)
location.replace("https://example.com/login");
// Reload the page
location.reload();
// Parse query params
const params = new URLSearchParams(location.search);
console.log(params.get("color")); // "red"// href redirect: navigates to /cart // replace: navigates to /login, no history entry // reload: refreshes the page "red"
3. window.history — Session Navigation
console.log(history.length); // number of entries in session history
history.back(); // go back one page (like clicking ←)
history.forward(); // go forward one page
history.go(-2); // go back 2 pages
history.go(0); // reload current page5 // back(): navigates to previous page // forward(): navigates to next page // go(-2): jumps back 2 entries // go(0): reloads
The History API (pushState / replaceState) is covered in its own dedicated lesson.
4. window.navigator — Browser & Device Info
console.log(navigator.userAgent);
console.log(navigator.language);
console.log(navigator.onLine);
console.log(navigator.platform);
console.log(navigator.hardwareConcurrency); // CPU logical cores"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ..." "en-US" true "Win32" 8
Feature detection (preferred over user-agent sniffing):
if ("geolocation" in navigator) {
console.log("GPS supported");
} else {
console.log("GPS not available");
}
if ("serviceWorker" in navigator) {
console.log("Service Workers supported");
}"GPS supported" "Service Workers supported"
5. window.screen — Display Info
console.log(screen.width); // total screen width
console.log(screen.height); // total screen height
console.log(screen.availWidth); // usable width (excludes taskbar)
console.log(screen.availHeight); // usable height
console.log(screen.colorDepth); // colour depth in bits2560 1440 2560 1400 24
6. Dialog Methods
// Synchronous dialogs (BLOCK the main thread — avoid in production UIs)
window.alert("Hello!"); // shows message, OK button
const ok = window.confirm("Delete?"); // returns true/false
const name = window.prompt("Name?", "Anonymous"); // returns string or null// alert: shows modal with "Hello!" // confirm: returns true if OK clicked, false if Cancel // prompt: returns entered string, or null if cancelled
⚠️ Warning:alert,confirm, andpromptfreeze the browser tab. Use custom modal libraries in real projects.
7. Timers
"Runs after 2 seconds" // ← after 2000ms "Runs every second" // ← every 1000ms until cleared
BOM vs DOM
| Feature | BOM | DOM |
|---|---|---|
| Root object | window | window.document |
| Controls | Browser itself | Page content (HTML/CSS) |
| Standardised | Loosely (convention) | W3C / WHATWG |
| Examples | location, history, navigator | querySelector, createElement |
When to Use BOM
- Redirect users after login/logout →
location.href - Detect online/offline status →
navigator.onLine - Read/write the URL hash for in-page anchors →
location.hash - Check screen size for responsive decisions →
screen.width - Schedule deferred work →
setTimeout - Feature detection before calling browser APIs →
"geolocation" in navigator
Common Mistakes
- Confusing
window.locationwith the History API —location.hrefcauses a full page load;history.pushStatedoes not. - Using
navigator.userAgentfor feature detection — it's unreliable. Use"feature" in navigatorinstead. - Blocking the thread with
alert()— replace with custom modals in real apps. - Not clearing intervals — forgetting
clearIntervalcauses memory leaks in SPAs. - Assuming
window.open()always works — pop-up blockers prevent it unless triggered by a user gesture. - Using
screen.widthfor responsive design — use CSS@mediaqueries orwindow.innerWidthfor viewport width.
Interview Questions
Q1. What is the BOM and how does it differ from the DOM?
The BOM (Browser Object Model) provides objects to interact with the *browser environment* (URL, history, device). The DOM (Document Object Model) represents and manipulates the *HTML content* of the page. The BOM is rooted atwindow; the DOM is rooted atwindow.document.
Q2. What is the difference between location.href = url and location.replace(url)?
location.href = urlperforms a redirect and adds a new entry to the session history, so the user can press Back.location.replace(url)navigates without adding a history entry — the current page is replaced, so Back goes to the page before it.
Q3. How do you detect if the user is offline in JavaScript?
Usenavigator.onLine(a boolean) and listen forwindowevents: ``js window.addEventListener("online", () => console.log("Back online")); window.addEventListener("offline", () => console.log("Gone offline"));``
Q4. Why should you avoid user-agent sniffing?
navigator.userAgentis easily spoofed and changes with every browser update, making it fragile. Feature detection ("geolocation" in navigator) checks whether the capability actually exists in the current browser, which is more reliable.
Q5. What does history.length return?
The number of entries in the current session's history stack, including the current page. It does not reveal the actual URLs for privacy reasons.
Q6. What is window.innerWidth vs screen.width?
window.innerWidthis the viewport width — the visible area inside the browser tab (changes when the window is resized).screen.widthis the total display resolution, regardless of browser size. UseinnerWidthfor responsive JavaScript logic.
Q7. How do you safely schedule code after a delay without causing a memory leak?
Always store the timer ID and clear it when the component/page unmounts: ``js const id = setTimeout(fn, 1000); // later: clearTimeout(id); ``Q8. What is globalThis and how does it relate to window?
globalThisis a standardised cross-environment reference to the global object. In browsers it equalswindow; in Node.js it equalsglobal. UsingglobalThismakes code portable across environments.
Key Takeaways
- The BOM is rooted at
window, the browser's global object. locationcontrols the URL;historycontrols navigation;navigatordescribes the browser/device;screendescribes the display.- Prefer feature detection (
"x" in navigator) over user-agent sniffing. location.hrefadds a history entry;location.replace()does not.- Timers (
setTimeout,setInterval) must be cleared to prevent memory leaks. - Avoid synchronous dialogs (
alert,confirm,prompt) in production UIs.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Browser Object Model (BOM) in JavaScript — Complete Guide.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, browser, apis, object
Related JavaScript Master Course Topics