Search code examples
javascriptwindow

JavaScript: What's the difference between window.top and top.window


I have been recently been reading into the JavaScript top functionality and noticed that I can run either window.top or top.window. From what I can see there is no difference in functionality so it seems to be strange that it is possible to run both.

// They appear to be the same here at least:
console.log(window.top === top.window);

MDN documentation

My question is, does anyone know why this functionality exists twice and are there any differences between the two? I am wondering about things like differences in browser support, or quirky bugs related to running it one way or another.


Solution

  • window is the global object, so properties on it can be accessed as if they were standalone variables. So referencing top on the top level is the same as referencing window.top. So the question boils down to the difference is between

    window.top
    

    and

    window.top.window
    

    window.top gives you a window object (it may be the same as window, or it may be an outer window, if you're in an iframe), and a window's window property is a reference to the same window object (it's a weird self-reference), so those two references are exactly the same as well. You can count on

    window.top === window.top.window
    

    to always be true.