w3resource

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:

// Define a function 'isBrowser' that checks if the code is running in a browser environment
const isBrowser = () => ![typeof window, typeof document].includes('undefined');

// Test cases to check if the code is running in a browser environment
console.log(isBrowser());  
console.log(isBrowser());

Output:

true
true

Flowchart:

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-203.php