1

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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • The `window.` is implicit in JavaScript an [can be omitted](https://off-tokyo.medium.com/understanding-javascript-window-object-cb0f082636e8). – Uwe Keim Aug 04 '23 at 07:05

2 Answers2

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.

khangnd
  • 323
  • 3
  • 11
  • except that in this case `indexedDB` is also available in the `WorkerGlobalScope` where there isn't a `window`. So the actual best practice here would be to write `globalThis.indexedDB` so that the code can be ran in both window and worker scopes. – Kaiido Aug 04 '23 at 09:14
-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.

Rasheeda
  • 6
  • 3