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
There’s no difference technical-wise, though adding
window.
to any properties of thewindow
object helps with the code readability in some cases. You can read more from this answer: https://stackoverflow.com/a/33305993/3916702.The difference between
indexedDB.open('test', 1)
andwindow.indexedDB.open('test', 1)
lies in the scope of the function. In JavaScript, thewindow
object is the global object that represents the browser window. Most objects and functions in the browser environment are properties of thewindow
object, includingindexedDB
.When you use
indexedDB.open('test', 1)
withoutwindow
, the JavaScript runtime will look for theindexedDB
function in the current scope and its parent scopes until it finds it, or it will throw an error if it cannot find it. IfindexedDB
is available in the global scope (which it usually is), then usingindexedDB.open('test', 1)
will work correctly.On the other hand,
window.indexedDB.open('test', 1)
explicitly specifies that theindexedDB
function should be looked up from thewindow
object. Sincewindow
is the global object, this is essentially equivalent toindexedDB.open('test', 1)
.In practice, both
indexedDB.open('test', 1)
andwindow.indexedDB.open('test', 1)
will achieve the same result, assumingindexedDB
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 globalwindow
object. However, it’s worth noting that in most cases, you can safely omitwindow
and useindexedDB.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.