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 whether the current runtime environment is a browser so that front-end modules can run on the server (Node) without throwing 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:

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.



JavaScript: Tips of the Day

How to check whether a string contains a substring in JavaScript?

ECMAScript 6 introduced String.prototype.includes:

const string = "foo";
const substring = "oo";

console.log(string.includes(substring));

includes doesn't have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:

var string = "foo";
var substring = "oo";

console.log(string.indexOf(substring) !== -1);

Ref: https://bit.ly/3fFFgZv