JavaScript JavaScript Basics (Retired) Storing and Tracking Information with Variables The Variable Challenge

Richie Black
Richie Black
27,272 Points

Variable name "location" concatenated into doc.write result redirects page. Why?

Initially I had this: . var name = prompt('Give a name'); var action = prompt('Give an action'); var location = prompt('Give a location'); var story = name + ' went ' + action + ' in ' + location + '.';

alert('You have entered all information'); document.write(story); . This would redirect the page to .../(valueStoredInLocation) which gives a 404. When changing the variable name to "loc" it works. Why does this redirect?

1 Answer

Steven Parker
Steven Parker
203,226 Points

The name "location" is a shorhand for "Window.location", which is a special object that controls what page the browser is displaying. Assigning something to it is also a special shorthand for assigning it's "href"property. And doing that causes the browser to treat that value as a URL and attempt to load a page from it.

For more details, see the MDN page on Window.location.