Reputation: 79
Is there any reason why should I use window.innerWidth
instead of innerWidth
?
Upvotes: 1
Views: 174
Reputation: 547
window.innerWidth
is always a property of the window object, so you're safe as long as a window exists (in other js environments like Node.js it doesn't), while innerWidth
refers to the global object only if there isn't already a variable with the same name in the current scope.
For example
// This logs the actual window.innerWidth
console.log(innerWidth);
function something() {
const innerWidth = 4;
// This innerWidth will not refer to the global object..
console.log(innerWidth);
}
// ..so this logs 4
something();
So either you remember all of the window
properties so you don't incur in conflicting variable names (not very handy and hard to debug) or you just access the window
object explicitly, making the code a little more verbose but also clearer and less error-prone.
Upvotes: 3