JavaScript: Determine whether the current runtime environment is a browser

JavaScript fundamental (ES6 Syntax): Exercise-203 with Solution

Write a JavaScript program to determine if the current runtime environment is a browser. This is so that front-end modules can run on the server (Node) without errors.

  • Use Array.prototype.includes() on the typeof values of both window and document (globals usually only available in a browser environment unless they were explicitly defined), which will return true if one of them is undefined.
  • typeof allows globals to be checked for existence without throwing a ReferenceError.
  • If both of them are not undefined, then the current environment is assumed to be a browser.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const isBrowser = () => ![typeof window, typeof document].includes('undefined');

console.log(isBrowser()); // true (browser)
console.log(isBrowser()); // false (Node)

Sample Output:



flowchart: Determine if the current runtime environment is a browser

Live Demo:

See the Pen javascript-basic-exercise-203-1 by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program that will return true whether the browser tab of the page is focused, false otherwise.
Next: Write a JavaScript program that will check whether the given argument is a native boolean element.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.