How come these to lines give different result ?
if (EventSource !== undefined) { // error
if (typeof(EventSource) !== 'undefined') { // no error
How come these to lines give different result ?
if (EventSource !== undefined) { // error
if (typeof(EventSource) !== 'undefined') { // no error
Because EventSource
is not declared, and it's considered a ReferenceError to request the value of an undeclared variable.
The typeof
operator on the other hand is able to take an identifier as an operand without getting its value, avoiding the error.
If this is a local variable, you should heed the ReferenceError, and define it first.
If this is global, and its existence can't be known beforehand, you can check it as a property of window
:
if ("EventSource" in window) {
or
if (window.EventSource !== undefined) {
The error you're seeing, ReferenceError: EventSource is not defined means that the JS engine has no idea who EventSource
is. It's never heard of it before and it should read something there, but it doesn't know what. The typeof
operator is protected from that error and returns 'undefined'
instead of throwing an error, just like it does for variables that haven't been initialized.
A variable that is declared without a value is undefined
.
A variable that is not declared throws an error when you try to use it, but when using typeof
you avoid that as checking an undeclared variable returns the type 'undefined'
.
It does this because typeof
is an operator (not a function) that always returns a string, even if you pass it something that is not previously declared.
From the ECMA-262 Standard draft:
8.7.1 GetValue (V): [...] If IsUnresolvableReference(V), throw a ReferenceError exception. [...]
11.4.3 The typeof Operator: [...] If Type(val) is Reference, then [...] If IsUnresolvableReference(val) is true, return "undefined". [...]
In short, they are different operations that follow different rules.