The JavaScript Browser Environment
When JavaScript runs in a browser, it gets access to a special environment with three main parts:
- ECMAScript โ the core language (variables, functions, loops, etc.)
- DOM (Document Object Model) โ APIs to interact with HTML/XML pages
- BOM (Browser Object Model) โ APIs to interact with the browser itself
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ JavaScript โ
โ โโโโโโโโโโโโ โโโโโโโโ โโโโโโโโโโ โ
โ โ JS โ โ DOM โ โ BOM โ โ
โ โ Language โ โ APIs โ โ APIs โ โ
โ โโโโโโโโโโโโ โโโโโโโโ โโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Global Object: window
In a browser, window is the global object. Every global variable, DOM API, and BOM method lives on it:
Demo: The window object
HTML
<p id='output'></p> JavaScript
const out = document.getElementById('output');
out.innerHTML = 'Window inner width: ' + window.innerWidth + 'px<br>';
out.innerHTML += 'Page location: ' + window.location.href; Live Output Window
DOM vs BOM
| DOM | BOM |
|---|---|
| Document Object Model | Browser Object Model |
document.getElementById() | navigator.userAgent |
document.querySelector() | location.href |
| Access/manipulate page content | Access/manipulate browser |
| Standardized by W3C | Partly standardized (HTML spec) |
DOM Specs
The DOM is maintained by the W3C and WHATWG. Modern browsers implement the DOM Living Standard which includes:
- Core DOM โ the tree structure model
- HTML DOM โ HTML-specific elements and attributes
- CSSOM โ CSS object model for styling
BOM APIs
The BOM provides browser-level objects:
navigatorโ browser info (user agent, geolocation, media devices)locationโ URL information and navigationhistoryโ session history (back, forward, pushState)screenโ screen dimensionsfetch/XMLHttpRequestโ network requestslocalStorage/sessionStorageโ client-side storage
Demo: BOM APIs in action
HTML
<p id='bom-output'></p> JavaScript
const el = document.getElementById('bom-output');
el.innerHTML = 'Browser: ' + navigator.userAgent + '<br>';
el.innerHTML += 'Platform: ' + navigator.platform + '<br>';
el.innerHTML += 'Screen size: ' + screen.width + 'x' + screen.height; Live Output Window
Key Takeaways
- JavaScript in the browser has three layers: language, DOM, BOM
windowis the global object โ all browser APIs hang off it- DOM lets you read and modify the page
- BOM lets you interact with the browser itself
- Both DOM and BOM are evolving standards โ always check compatibility