Check Operating System in JavaScript

- 1 minute read

I love this JavaScript snippet, because it does one job well and concisely. It’ll determine the current operating system of the user:

const getOperatingSystem = () => {
    let os = `Undetected`;

    if (navigator.appVersion.indexOf(`Win`) != -1) os = `Windows`;
    else if (navigator.appVersion.indexOf(`Mac`) != -1) os = `MacOS`;
    else if (navigator.appVersion.indexOf(`Linux`) != -1) os = `Linux`;
    else if (navigator.appVersion.indexOf(`X11`) != -1) os = `UNIX`;

    return os;

It can be used by simply calling the getOperatingSystem() function:

const operatingSystem = getOperatingSystem();

Keep in mind that the navigator.appVersion string, which this snippet derives its result from, can be faked.

Link to this section Conclusion

There are other methods to get more advanced insights into the user’s operating system and version, but that is beyond the scope of this article.

As of writing this, navigator.appVersion has full browser support, but it may be deprecated or partially deprecated in the future. If that’s the case, then consider migrating to navigator.userAgent.

Anyway, I hope this helped you!