Sometimes, we want to get the device width in JavaScript.
In this article, we’ll look at how to get the device width in JavaScript.
How to get the device width in JavaScript?
To get the device width in JavaScript, we use the window.innerWidth or screen.width properties.
For instance, we write
const width = window.innerWidth > 0 ? window.innerWidth : screen.width;
to check if window.innerWidth is bigger than 0.
If it is, then we return that as the width.
Otherwise, we return screen.width.
window.innerWidth is available in the desktop.
And screen.width is available on mobile devices.
Conclusion
To get the device width in JavaScript, we use the window.innerWidth or screen.width properties.