What is the purpose of calling
if (typeof window !== 'undefined')
I saw it in JSPM plugin-css, and some other libraries.
It's an idiomatic check to see if the script is being run in a web-page inside a web-browser or not.
One might assume that JavaScript only runs in web-pages as that's what it was originally designed for, but this isn't true: JavaScript is a versatile language that can also be used for writing server-side code in Node.js or IIS' Active Server Pages (since 1996!), or inside "web workers", which are scripts for web-pages that run in the background.
In a webpage, there are several intrinsic objects, such as window
, other environments (like Node.js) won't have window
but might have other objects like console
(well, console
now exists in most browsers now, but it wasn't originally).
For example, in different contexts different objects are available in the script's global scope (this list is not exhaustive):
Math
and Date
Object
, Number
, Function
, String
, etc (objects representing built-in types), etc<script>
tags):
Window
(interface) is exposed as the window
global object, which is also the object that is the global scope (so declaring var foo
in the global scope actually creates a property window.foo
!)document
global-object is actually accessing the window.document
property.window
global object nor properties like document
or navigator
, but you do get other global objects like:console
process
exports
window
object either, so instead the global scope is an WindowOrWorkerGlobalScope
object which exposes objects via properties like:caches
indexedDB
origin
response
(for writing to the response stream)request
(for reading from the incoming HTTP request)Application
and Session
(for persisting data between requests)WScript
global object exposes functionality from the script host.