Setting the global location
causes the browser to go to that URL. It’s not a reserved word1 — it’s a property defined on the global object (globalThis
, which is window
in the Web).
In your example, you are setting the global location
to "Los Angeles"
, which causes the browser to navigate to that as if it was a relative URL.
Setting var location = "San Francisco"
inside your function has no effect on the window object because the running execution context inside a function has its own variable environment, which is different from the one in global scope.
So you could do this:
function showLocation() {
var location = "San Francisco";
document.write(location)
}
and it will work as expected. It will write the string "San Francisco"
to the document.
If you are on a modern browser, you can see what’s going on by trying so set 'location' with 'let':
let location = "los angeles";
Now you will get an error that says something like:
SyntaxError
: Can’t create duplicate variable that shadows a global property: 'location
'.
1: If you want to know what the reserved words are in JavaScript, take a look at the MDN documentation.