Assigning `var location` in global scope redirects to non-existent file

945 Views Asked by At

I have an HTML file test.html where I have two variables both named location, one global and one local. But when I open it in browser it just says Your file was not found, and the address bar shows file://Los%20Angeles instead of file://test.html as expected. Why?

<html>
<body>
<script type="text/javascript">
var location = "Los Angeles"
function showLocation() {
    var location = "San Francisco"
    document.write(location)
}
</script>
<input type="button" onclick="showLocation()" value="Show Location"/>
</body>
</html>
2

There are 2 best solutions below

4
On BEST ANSWER

'location' is a reserved keyword in javascript. Just change your variable name into something else. For more info about reserved words: https://www.w3schools.com/js/js_reserved.asp

1
On

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.