javascriptwindow.location

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


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>

Solution

  • '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