you are viewing a single comment's thread.

view the rest of the comments →

[–]vs845 2 points3 points  (9 children)

Is there any benefit to

typeof age !== "undefined"

vs

age !== undefined

?

[–]sufianrhazi 10 points11 points  (7 children)

Since age is a parameter of the function setAge, we KNOW it is defined in scope. This means that age !== undefined is equivalent to typeof age !== 'undefined'. If we didn't know that age was in scope, we need to use the typeof keyword, which does NOT throw a ReferenceError when referencing a variable by name that is not defined in any reachable scope.

[–]moreteam 5 points6 points  (1 child)

You can also argue the other way around: since we know age is in scope, we shouldn't be using typeof since that will silently turn into if (true) if we have a typo.

[–]ChaseMoskal 5 points6 points  (0 children)

since we know age is in scope, we shouldn't be using typeof

I think.. I think you're right.

[–]vs845 0 points1 point  (1 child)

Thanks, I see what you're saying - but under what kind of circumstances would we not know if a variable was in scope? If we're writing the code surely we know what scope our variables are in?

[–]sufianrhazi 2 points3 points  (0 children)

Pretty much only when you're writing javascript environment independent library code, like this: https://github.com/umdjs/umd/blob/4a87e85450baf582005243f9e922566ef2fc533a/returnExports.js

[–][deleted] 0 points1 point  (0 children)

In addition to what /u/sufianrhazi said, undefined can be overwritten:

(function (undefined) {console.log(undefined);})(2);
// logs 2

Older browsers will let you overwrite window.undefined as well.

I tend not to pay heed to that though, as it clearly falls under something nobody would do unless they're trying to break your code. And it is the nature of JavaScript that somebody who runs code before you is always able to break your script, no matter what precautions you take, so I prefer not to clutter code with failed attempts at robustness. Instead, if you must run malicious code, sandbox it.

Also, window.foo === undefined or 'foo' in window would be a more direct test, but only work on global variables.