JavaScript Execution Context and Sandboxing
You'll learn how browsers isolate JavaScript code to prevent it from compromising your system or other sites.
What Is a Sandbox?
Think of JavaScript running in your browser like a child playing in a sandbox at a playground. The sandbox has walls that keep the child safely contained—they can build castles and dig holes inside, but they can't wander into traffic or enter someone's house. Similarly, browsers create isolated environments where JavaScript can run without directly accessing your operating system, files, or other websites' data.
Execution Context and Global Scope
When JavaScript runs in a browser, it operates within an execution context—a controlled environment that defines what the code can see and do. Each browser tab or frame gets its own global scope (like the window object), which acts as the top-level container for all variables and functions in that context.
JavaScript cannot break out of this context to:
- Read or write arbitrary files on your hard drive
- Access memory from other tabs or applications
- Execute system commands
- Make network requests to any domain without CORS restrictions
Why This Matters for Security
Sandboxing is your first line of defense against malicious JavaScript. Even if you visit a compromised website, the attacker's code is trapped inside the sandbox. They can't install malware, steal files from your desktop, or access data from your banking site open in another tab.
The browser enforces same-origin policy, ensuring scripts from evil.com cannot access cookies, localStorage, or DOM content from bank.com.
Key Takeaway: Browsers sandbox JavaScript execution to prevent direct system access and isolate different origins, forming the foundation of client-side web security.