Why is Javascript "safe" to work in the browser?

The browser isolates JavaScript because it runs in a browser process itself. It can not do anything that is not allowed by the browser's JavaScript interpreter or the JIT compiler. However, because of its complexity, it is not uncommon to find vulnerabilities allowing JavaScript to compromise the browser and to obtain arbitrary code execution with browser process privileges.

Because these types of security issues are so common, many browsers will implement a sandbox. This is a protection mechanism that attempts to isolate a compromised browser process and prevent it from further harm. The operation of the sandbox depends on the browser. Firefox has very limited sandboxing, while Chrome and Edge have significant sandboxing. However, despite this defense in depth, browser vulnerabilities can often be combined with sandbox escape vulnerabilities.