skip to Main Content

I see that some people use this way const request = indexedDB.open('test', 1); and some others use this one const request = window.indexedDB.open('test', 1);.

Could you please tell me what is the difference and what is the best way?

I’m just trying to learn the best way to open an indexedDB.

2

Answers


  1. There’s no difference technical-wise, though adding window. to any properties of the window object helps with the code readability in some cases. You can read more from this answer: https://stackoverflow.com/a/33305993/3916702.

    Login or Signup to reply.
  2. The difference between indexedDB.open('test', 1) and window.indexedDB.open('test', 1) lies in the scope of the function. In JavaScript, the window object is the global object that represents the browser window. Most objects and functions in the browser environment are properties of the window object, including indexedDB.

    When you use indexedDB.open('test', 1) without window, the JavaScript runtime will look for the indexedDB function in the current scope and its parent scopes until it finds it, or it will throw an error if it cannot find it. If indexedDB is available in the global scope (which it usually is), then using indexedDB.open('test', 1) will work correctly.

    On the other hand, window.indexedDB.open('test', 1) explicitly specifies that the indexedDB function should be looked up from the window object. Since window is the global object, this is essentially equivalent to indexedDB.open('test', 1).

    In practice, both indexedDB.open('test', 1) and window.indexedDB.open('test', 1) will achieve the same result, assuming indexedDB is available in the global scope, which is the case in modern browsers. Therefore, using either of them is acceptable, and it comes down to personal preference and coding style.

    For consistency and clarity, some developers may choose to use window.indexedDB.open('test', 1) to make it explicit that they are accessing a function from the global window object. However, it’s worth noting that in most cases, you can safely omit window and use indexedDB.open('test', 1).

    So, either way, you can open an indexedDB database effectively. If indexedDB is available globally (as it should be in the browser environment), then both ways are functionally identical. Choose the one that fits your coding style and preference.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search