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 said 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 Answers

3
Kavindra On Best Solutions

'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
Mark Meyer On

Setting the global location causes the browser to go to that url. It's not a reserved word — it's a variable defined on the window object. Here is a better list of reserved words:

https://docs.microsoft.com/en-us/scripting/javascript/reference/javascript-reserved-words

In your example, you are setting the global location to 'Los Angeles', which causes the window 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 function variables have their own 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'