Is there any reason why should I use window.innerWidth
instead of innerWidth
?
Asked
Active
Viewed 102 times
0

hommat
- 69
- 1
- 6
-
1Someone can create a variable named `innerWidth` and you wouldn't get desired result – Sebastian Kaczmarek Feb 27 '20 at 15:04
-
Possible duplicate of [window.variableName](https://stackoverflow.com/q/11148997/1823841) – palaѕн Feb 27 '20 at 15:05
-
Also, it's clearer at a glance what the innerWidth is referencing. – Feb 27 '20 at 15:15
1 Answers
1
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.

NevNein
- 487
- 4
- 14