Related
So, this is apparently not allowed in Javascript today?
<script>
if (fbq == null) {
fbq('track', 'ViewContent');
}
</script>
Console returns this:
And also this in the web inspector:
I thought this was pretty standard code? Surely?
Ignore the fact that fbq is undefined when called on line 142. It doesn't even get there. The error happens on line 141. I've tried testing for "typeof fbq" etc, and always returns the undefined error. Bizarre.
You can simply do:
typeof fbq || fbq === null // undefined
The typeof operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.
Try this,
if (typeof(fbq) =='undefined' || fbq == null) {
fbq('track', 'ViewContent');
}
As mentioned by #sanjay typeof operator doesn't throw ReferenceError exception when used on undefined variable.
From Mozilla:
The value null is written with a literal: null. null is not an
identifier for a property of the global object, like undefined can be.
Instead, null expresses a lack of identification, indicating that a
variable points to no object. In APIs, null is often retrieved in a
place where an object can be expected but no object is relevant.
// foo does not exist. It is not defined and has never been initialized:
foo;
"ReferenceError: foo is not defined"
// foo is known to exist now but it has no type or value:
var foo = null;
foo;
"null"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null
I believe that's how it behaves. If you have a look at the spec, it says:
7.2.12 Abstract Equality Comparison
The comparison x == y, where x and y are values, produces true or
false. Such a comparison is performed as follows:
If x is null and y is undefined, return true.
If x is undefined and y is null, return true.
Return false.
http://www.ecma-international.org/ecma-262/6.0/#sec-abstract-equality-comparison
So basically if you try something like:
undefined == null // this should return true.
But you cannot use a reference which you have not defined. In my opinion, a good test to see if the variable is defined is to do something like below.
typeof variable !== 'undefined'
Feel free to ask if you need further clarifications :)
I swear I was trying permutations of this earlier and it was also throwing the same error, but isn't now? Weird stuff going on in my browser for the last hour. Very frustrating, but this works:
<script>
if (!(typeof fbq || fbq === null)) {
fbq('track', 'ViewContent');
}
</script>
Just updated the script to use Sanjay's code instead of mine (which also worked).
I realize that this question is extremely similar to many others, but I must be missing some nuance with checking whether a variable is set or not. I have seen this in other developers code:
if(foo){
doSomething(foo);
}
else{
alert('error of whatever');
}
With the intent that the doSomething() will only execute if foo is set or not undefined. However, when I google this, it seems everyone says "typeof" should be used instead of the above method. I specifically see this in use with angular, like this:
if($scope.property){
dothis();
}
Am I missing something? When I see the above code, it seems to work, but all the answers I see never say this is the correct way to check if something is set or exists.
For if() checks, in MOST scenarios where you are checking for the existence of a property on an object (your situation), what you have described is perfectly valid, easy and convenient. It checks for the existence of the property and returns true if it exists.
However, there are plenty of nuanced areas where a typeof check is "more" correct, particularly if your type is being coerced in any way via == or if you want to differentiate between null and undefined.
For instance, if null is a valid value for your property to have but undefined is not, in your example dothis() would still be called. You would prevent this with a typeof check.
if (typeof $scope.property === 'undefined') {
dothis();
}
Finally, if you are checking for the existence of a variable instead of the existence of a property, an exception will be thrown if the variable you are checking is not defined, forcing you to use a typeof check.
In those scenarios, verbosity is your friend.
This has to do with the concept of "truthiness". Any value besides false, 0, "", null, undefined, and NaN is "truthy" which means the first block of the if-statement will run. For instance:
if ("") {
alert("falsie"); // won't run because the empty string ("") is falsie
} else {
alert("truthie"); // will run
}
whereas
if ("something") {
alert("truthy"); // will run because "something" is truthy
} else {
alert("falsie"); // won't run
}
Going back to your example, if foo is truthy (meaning that it has ANY value other than false, 0, "", null, undefined, and NaN) then it will run the first block of the if-statement (which has the doSomething() function in it).
You could also use short circuit evaluation and do this in one line.
($scope.property && doThis())
It is better to use typeof if you need to explicitly check whether the value is undefined or not. If you just want to check if the value is truthy, then you don't need typeof.
The reason the typeof operator is preferred is because it doesn't throw a ReferenceError exception when used with an undeclared variable.
However, it is important to note that variables initialized as null will return "object", so to avoid this issue, the following code is recommended:
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
What you are checking this way is if foo is not:
false
Undefined
Null
+0, −0, or NaN
Empty String
More info here:
https://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/
This way your function is only executed if foo is valid.
You may want to be more specific and check against a certain type with typeof.
var foo = 'foo';
if (typeof foo === 'string') { // true
doSomething();
}
The typeof operator returns a string indicating the type of the
unevaluated operand.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
I've been working on a javascript library, and I have a lot of redundant checks like this:
if(typeof foo !== "undefined" && foo !== null)
So, I wanted to create a function that will be a shortcut to this unwieldy check. So I came up with this:
function isset(a)
{
return (typeof a !== "undefined" && a !== null) ? true : false;
}
But, since the value could be undefined, and it attempts to use a possibly undefined variable, it turns out to be useless.
Is there a way to accomplish this without have to extend a native prototype?
It really depends on what you mean by undefined.
1. You mean the variable does not exist.
In this case, what you want is not possible. typeof is an operator and therefore has magic behavior you just can't emulate using the language. If you try to pass a variable that doesn't exist to your function, it will throw a ReferenceError.
(See below for a workaround.)
2. You mean the variable has the value undefined, but does exist.
In this case, your function will do the trick -- though it could be simplified to the following:
function isset(variable) {
return variable != null;
}
This function will return false if the variable is either undefined or null. It takes advantage of the fact that undefined == null in JavaScript. Of course, with such a short function, one could argue that the function isn't needed at all.
Recall that a variable that is declared has a value -- undefined -- by default.
The name of your function suggests you mean case #1. I don't know what sort of library you are writing, but I can't imagine a case in a library where you would need to check if a variable exists, though I can definitely think of many possibilities for case #2.
If case #1 is necessary, remember that you can re-declare variables without changing their value:
a = 1; // pretend this was set somewhere higher up in the code
var a; // this does not change the value of `a`
If you re-declare variables before you use isset, you could avoid the ReferenceError problem. You won't be able to tell if the code has already declared the variable, though; you will only be able to tell if they have not assigned it to some other value.
You can check for null and undefined at the same time by using != instead.
// checks for both null and undefined
if( foo != null ) { ...
...so no need to use a function to shorten it.
null and undefined also evaluates to false in an if statement. So the following statement also works:
if(!foo)
...
This should cut it down significantly.
I do not understand why people keep promoting if (var) or if (!var). Both fail in my browsers. Meantime if (obj.prop) passes. This means that we should use if (this.someVar) or if (window.someVar) instead of if (varbl). Ok?
I've been writing JavaScript for quite a long time now, and I have never had a reason to use null. It seems that undefined is always preferable and serves the same purpose programmatically. What are some practical reasons to use null instead of undefined?
I don't really have an answer, but according to Nicholas C. Zakas, page 30 of his book "Professional JavaScript for Web Developers":
When defining a variable that is meant
to later hold an object, it is
advisable to initialize the variable
to null as opposed to anything else.
That way, you can explicitly check for the value null to determine if
the variable has been filled with an object reference at a later time
At the end of the day, because both null and undefined coerce to the same value (Boolean(undefined) === false && Boolean(null) === false), you can technically use either to get the job done. However, there is right way, IMO.
Leave the usage of undefined to the JavaScript compiler.
undefined is used to describe variables that do not point to a reference. It is something that the JS compiler will take care for you. At compile time the JS engine will set the value of all hoisted variables to undefined. As the engine steps through the code and values becomes available the engine will assign respective values to respective variables. For those variables for whom it did not find values, the variables would continue to maintain a reference to the primitive undefined.
Only use null if you explicitly want to denote the value of a variable as having "no value".
As #com2gz states: null is used to define something programmatically empty. undefined is meant to say that the reference is not existing. A null value has a defined reference to "nothing". If you are calling a non-existing property of an object, then you will get undefined. If I would make that property intentionally empty, then it must be null so you know that it's on purpose.
TLDR; Don't use the undefined primitive. It's a value that the JS compiler will automatically set for you when you declare variables without assignment or if you try to access properties of objects for which there is no reference. On the other hand, use null if and only if you intentionally want a variable to have "no value".
Sidebar: I, personally, avoid explicitly setting anything to undefined (and I haven't come across such a pattern in the many codebases/third party libs I've interacted with). Also, I rarely use null. The only times I use null is when I want to denote the value of an argument to a function as having no value, i.e.,:
function printArguments(a,b) {
console.log(a,b);
}
printArguments(null, " hello") // logs: null hello
null and undefined are essentially two different values that mean the same thing. The only difference is in the conventions of how you use them in your system. As some have mentioned, some people use null for meaning "no object" where you might sometimes get an object while undefined means that no object was expected (or that there was an error). My problem with that is its completely arbitrary, and totally unnecessary.
That said, there is one major difference - variables that aren't initialized (including function parameters where no argument was passed, among other things) are always undefined.
Which is why in my code I never use null unless something I don't control returns null (regex matching for example). The beauty of this is it simplifies things a lot. I never have to check if x === undefined || x === null, I can just check x === undefined. And if you're in the habit of using == or simply stuff like if(x) ... , stop it.
!x will evaluate to true for an empty string, 0, null, NaN - i.e. things you probably don't want. If you want to write javascript that isn't awful, always use triple equals === and never use null (use undefined instead). It'll make your life way easier.
undefined is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null is where the thing is known to exist, but it has no value.
Everyone has their own way of coding and their own internal semantics, but over the years I have found this to be the most intuitive advice that I give people who ask this question: when in doubt, do what JavaScript does.
Let's say you are working with object properties like options for a jQuery plugin...ask yourself what value JavaScript gives a property that has yet to be defined -- the answer is undefined. So in this context, I would initialize these types of things with 'undefined' to be consistent with JavaScript (for variables, you can do var myVar; instead of var myVar = undefined;).
Now let's say you are doing DOM manipulation...what value does JavaScript assign to non-existent elements? The answer is null. This is the value I would initialize with if you are creating a placeholder variable that will later hold a reference to an element, document fragment, or similar that relates to the DOM.
If you're working with JSON, then a special case needs to be made: for undefined property values, you should either set them to "" or null because a value of undefined is not considered proper JSON format.
With this said, as a previous poster has expressed, if you find that you're initializing stuff with null or undefined more than once in a blue moon, then maybe you should reconsider how you go about coding your app.
You might adopt the convention suggested here, but there really is no good reason to. It is not used consistently enough to be meaningful.
In order to make the convention useful, you first must know that the called function follows the convention. Then you have to explicitly test the returned value and decide what to do. If you get undefined, you can assume that some kind of error occurred that the called function knew about. But if an error happened, and the function knew about it, and it is useful to send that out into the wider environment, why not use an error object? i.e. throw an error?
So at the end of the day, the convention is practically useless in anything other than very small programs in simple environments.
A few have said that it is ok to initialise objects to null. I just wanted to point out that destructuring argument defaults don't work with null. For example:
const test = ({ name } = {}) => {
console.log(name)
}
test() // logs undefined
test(null) // throws error
This requires performing null checks prior to calling the function which may happen often.
A useful property in null that undefined does not qualifies:
> null + 3
3
> undefined + 3
NaN
I use null when I want to 'turn off' a numeric value,
or to initialize some. My last use was manipulating css transform:
const transforms = { perspective : null, rotateX : null };
// if already set, increase, if not, set to x
runTimeFunction((x) => { trasforms.perspective += x; });
// still useful, as setting perspective to 0 is different than turning it off
runTimeFunction2((x) => { transforms.perspective = null; });
// toCss will check for 'null' values and not set then at all
runTimeFunction3(() => { el.style.transform = toCss(transforms); });
Not sure if I should use this property thought...
DOM nodes and elements are not undefined, but may be null.
The nextSibling of the last child of an element is null.
The previousSibling of the first child is null.
A document.getElementById reference is null if the element does not exist in the document.
But in none of these cases is the value undefined; there just is no node there.
Unknown variable: undefined.
Known variable yet no value: null.
You receive an object from a server, server_object.
You reference server_object.errj. It tells you it’s undefined. That means it doesn’t know what that is.
Now you reference server_object.err. It tells you it’s null. That means you’re referencing a correct variable but it’s empty; therefore no error.
The problem is when you declare a variable name without a value (var hello) js declares that as undefined: this variable doesn’t exist; whereas programmers mostly mean: “I’ve not given it a value yet”, the definition of null.
So the default behavior of a programmer—declaring a variable without a value as nothing—is at odds with js—declaring it as not existing. And besides, !undefined and !null are both true so most programmers treat them as equivalent.
You could of course ensure you always do var hello = null but most won’t litter their code as such to ensure type sanity in a deliberately loosely-typed language, when they and the ! operator treat both undefined and null as equivalent.
In JavaScript, the value null represents the intentional absence of any object value. null expresses a lack of identification, indicating that a variable points to no object.
The global undefined property represents the primitive value undefined.
undefined is a primitive value automatically assigned to variables.
undefined is meant to say that the reference is not existing.
I completely disagree that usage null or undefined is unnecessary.
undefined is thing which keeping alive whole prototype chaining process.
So compiler only with null can't check if this property just equal to null, or its not defined in endpoint prototype. In other dynamic typed languages(f.e. Python) it throws exception if you want access to not defined property, but for prototype-based languages compiler should also check parent prototypes and here are the place when undefined need most.
Whole meaning of using null is just bind variable or property with object which is singleton and have meaning of emptiness,and also null usage have performance purposes. This 2 code have difference execution time.
var p1 = function(){this.value = 1};
var big_array = new Array(100000000).fill(1).map((x, index)=>{
p = new p1();
if(index > 50000000){
p.x = "some_string";
}
return p;
});
big_array.reduce((sum, p)=> sum + p.value, 0)
var p2 = function(){this.value = 1, p.x = null};
var big_array = new Array(100000000).fill(1).map((x, index)=>{
p = new p2();
if(index > 50000000){
p.x = "some_string";
}
return p;
});
big_array.reduce((sum, p)=> sum + p.value, 0)
I'm working through this exact question right now, and looking at the following philosophy:
Any function that is intended to return a result should return null if it fails to find a result
Any function that is NOT intended to return a result implicitly returns undefined.
For me, this question is significant because anyone calling a function that returns a result should have no question as to whether to test for undefined vs null.
This answer does not attempt to address:
Property values of null vs undefined
Variables within your functions being null vs undefined
In my opinion, variables are your own business and not a part of your API, and properties in any OO system are defined and therefore should be defined with value different from what they would be if not defined (null for defined, undefined is what you get when accessing something that is not in your object).
Here's a reason: var undefined = 1 is legal javascript, but var null = 1 is a syntax error. The difference is that null is a language keyword, while undefined is, for some reason, not.
If your code relies on comparisons to undefined as if it's a keyword (if (foo == undefined) -- a very easy mistake to make) that only works because nobody has defined a variable with that name. All that code is vulnerable to someone accidentally or maliciously defining a global variable with that name. Of course, we all know that accidentally defining a global variable is totally impossible in javascript...
Just wanna add that with usage of certain javascript libraries, null and undefined can have unintended consequences.
For example, lodash's get function, which accepts a default value as a 3rd argument:
const user = {
address: {
block: null,
unit: undefined,
}
}
console.log(_.get(user, 'address.block', 'Default Value')) // prints null
console.log(_.get(user, 'address.unit', 'Default Value')) // prints 'Default Value'
console.log(_.get(user, 'address.postalCode', 'Default Value')) // prints 'Default Value'
Another example: If you use defaultProps in React, if a property is passed null, default props are not used because null is interpreted as a defined value.
e.g.
class MyComponent extends React.Component {
static defaultProps = {
callback: () => {console.log('COMPONENT MOUNTED')},
}
componentDidMount() {
this.props.callback();
}
}
//in some other component
<MyComponent /> // Console WILL print "COMPONENT MOUNTED"
<MyComponent callback={null}/> // Console will NOT print "COMPONENT MOUNTED"
<MyComponent callback={undefined}/> // Console WILL print "COMPONENT MOUNTED"
There are already some good answers here but not the one that I was looking for. null and undefined both "technically" do the same thing in terms of both being falsy, but when I read through code and I see a "null" then I'm expecting that it's a user defined null, something was explicitly set to contain no value, if I read through code and see "undefined" then I assume that it's code that was never initialized or assigned by anything. In this way code can communicate to you whether something was caused by uninitialized stuff or null values. Because of that you really shouldn't assign "undefined" manually to something otherwise it messes with the way you (or another developer) can read code. If another developer sees "undefined" they're not going to intuitively assume it's you who made it undefined, they're going to assume it's not been initialized when in fact it was. For me this is the biggest deal, when I read code I want to see what it's telling me, I don't want to guess and figure out if stuff has "actually" been initialized.
Not even to mention that using them in typescript means two different things. Using:
interface Example {
name?: string
}
Means that name can be undefined or a string, but it can't be null. If you want it null you have to explicitly use:
interface Example {
name: string | null
}
And even then you'll be forced to initialize it at least with "null".
That's of course only true if you're using "strictNullChecks": true in tsconfig.json.
Based on a recent breakage we ran into, the example below shows why I prefer to use undefined over null, unless there is a specific reason to do otherwise:
function myfunc (myArg) {
if (typeof myArg === 'string') {
console.log('a', myArg);
} else if (typeof abc === 'object') {
console.log('b', myArg);
if (myArg.id) {
console.log('myArg has an id');
} else {
console.log('myArg has an id');
}
} else {
console.log('no value');
}
}
The following values will play nicely:
'abc'
{}
undefined
{ id: 'xyz' }
On the other hand the assumption of null and undefined being equivalent here breaks the code. The reason being is that null is of type of object, where as undefined is of type undefined. So here the code breaks because you can't test for a member on null.
I have seen a large number of cases with code of similar appearance, where null is just asking for problems:
if (typeof myvar === 'string') {
console.log(myvar);
} else if (typeof myvar === 'object') {
console.log(myvar.id);
}
The fix here would be to explicitly test for null:
if (typeof myvar === 'string') {
console.log(myvar);
} else if (myvar !== null && typeof myvar === 'object') {
console.log(myvar.id);
}
My attitude is to code for the weaknesses of a language and the typical behaviours of programmers of that language, hence the philosophy here of going with 'undefined' bey default.
To write simple code you need to keep complexity and variation down. When a variable or a property on an object does not have a value it is undefined , and for a value to be null you need to assign it a null value.
Undeclared vs Null
null is both an Object "type" and one of the 7 unique primitive value types called null
undefined is both a global scope property and type called undefined and one of the 7 unique primitive value types called undefined (window.undefined) .
It is the primitive types we use as values we are interested in.
In the case of null, as a value type it means an empty value has been assigned to a variable, but the variable type (Number, String, etc) is still defined. It just has no value. That is what null means. It means a variable has an empty value but it is still a value. It also reinitializes the variable with some kind of value, but is not undefined as a type.
undefined is a special case. When you declare a variable (or use a missing value not yet declared) it is of type undefined, as the browser does not know what type of data has been assigned to it yet. If the variable is declared but not assigned a value is is assigned the primitive calue undefined by default prior to assigning a value, and implies the variable does not exist or exists but has no value assigned.
Like null, undefined is also a primitive value type. But unlike null it means the variable does not exist, where null means the value does not exist. That is why its always better to check if the variable exists and has been assigned a variable using undefined before checking if the value is null or empty. undefined implies no variable or object exists in the compilation at all. The variable has either not been declared or declared with a missing value so not initialized. So checking for undefined is a very good way to avoid many types of errors in JavaScript and supersedes null.
That is why I would not rely on "truthy" checks for true/false with null and undefined, even though they will both return a false response, as undefined implies an additional step for missing feature, object, or variable, not just a true/false check. It implies something more. If you have a missing undeclared variable, truthy statements will trigger an ERROR!
Let's look at undefined first:
//var check1;// variable doesnt even exist so not assigned to "undefined"
var check2;// variable declared but not initialized so assigned "undefined"
var check3 = 'hello world';// variable has a value so not undefined
console.log('What is undefined?');
//console.log(check1 === undefined);// ERROR! check1 does not exist yet so not assigned undefined!
console.log(check2 === undefined);// True
console.log(check3 === undefined);// False
console.log(typeof check1 === 'undefined');// True - stops the ERROR!
console.log(typeof check2 === 'undefined');// True
console.log(typeof check3 === 'undefined');// False
As you can see undeclared variables, or declared but not initialized, both are assigned a type of undefined. Notice declared variables that are not initialized are assigned a value of undefined, the primitive value type but variables that do not exist are undefined types.
null has nothing to do with missing variables or variables not yet assigned values, as null is still a value. So anything with a null is already declared and initialized. Also notice a variable assigned a null value is actually an object type unlike undefined types. For example...
var check4 = null;
var check5 = 'hello world';
console.log('What is null?');
console.log(check4 === undefined);// False
console.log(check5 === undefined);// False
console.log(typeof check4 === 'undefined');// False
console.log(typeof check5 === 'undefined');// False
console.log(typeof check4);// return 'object'
console.log(typeof check5);// return 'string'
As you can see each act differently and yet both are primitive values you can assign any variable. Just understand they represent different states of variables and objects.
The jQuery Core Style Guidelines suggest two different ways to check whether a variable is defined.
Global Variables: typeof variable === "undefined"
Local Variables: variable === undefined
Properties: object.prop === undefined
Why does jQuery use one approach for global variables and another for locals and properties?
For undeclared variables, typeof foo will return the string literal "undefined", whereas the identity check foo === undefined would trigger the error "foo is not defined".
For local variables (which you know are declared somewhere), no such error would occur, hence the identity check.
I'd stick to using typeof foo === "undefined" everywhere. That can never go wrong.
I imagine the reason why jQuery recommends the two different methods is that they define their own undefined variable within the function that jQuery code lives in, so within that function undefined is safe from tampering from outside. I would also imagine that someone somewhere has benchmarked the two different approaches and discovered that foo === undefined is faster and therefore decided it's the way to go. [UPDATE: as noted in the comments, the comparison with undefined is also slightly shorter, which could be a consideration.] However, the gain in practical situations will be utterly insignificant: this check will never, ever be any kind of bottleneck, and what you lose is significant: evaluating a property of a host object for comparison can throw an error whereas a typeof check never will.
For example, the following is used in IE for parsing XML:
var x = new ActiveXObject("Microsoft.XMLDOM");
To check whether it has a loadXML method safely:
typeof x.loadXML === "undefined"; // Returns false
On the other hand:
x.loadXML === undefined; // Throws an error
UPDATE
Another advantage of the typeof check that I forgot to mention was that it also works with undeclared variables, which the foo === undefined check does not, and in fact throws a ReferenceError. Thanks to #LinusKleen for reminding me. For example:
typeof someUndeclaredVariable; // "undefined"
someUndeclaredVariable === undefined; // throws a ReferenceError
Bottom line: always use the typeof check.
Yet another reason for using the typeof-variant: undefined can be redefined.
undefined = "foo";
var variable = "foo";
if (variable === undefined)
console.log("eh, what?!");
The result of typeof variable cannot.
Update: note that this is not the case in ES5 there the global undefined is a non-configurable, non-writable property:
15.1.1 Value Properties of the Global Object
[...]
15.1.1.3 undefined
The value of undefined is undefined (see 8.1). This property has the attributes
{ [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.
But it still can be shadowed by a local variable:
(function() {
var undefined = "foo";
var variable = "foo";
if (variable === undefined)
console.log("eh, what?!");
})()
or parameter:
(function(undefined) {
var variable = "foo";
if (variable === undefined)
console.log("eh, what?!");
})("foo")
Who is interested in the performance gain of variable === undefined, may take a look here, but it seems to be a chrome optimization only.
http://jsperf.com/type-of-undefined-vs-undefined/30
http://jsperf.com/type-of-undefined-vs-undefined
Because undefined is not always declared, but jQuery declares undefined in its main function. So they use the safe undefined value internally, but outside, they use the typeof style to be safe.
For local variables, checking with localVar === undefined will work because they must have been defined somewhere within the local scope or they will not be considered local.
For variables which are not local and not defined anywhere, the check someVar === undefined will throw exception: Uncaught ReferenceError: j is not defined
Here is some code which will clarify what I am saying above. Please pay attention to inline comments for further clarity.
function f (x) {
if (x === undefined) console.log('x is undefined [x === undefined].');
else console.log('x is not undefined [x === undefined.]');
if (typeof(x) === 'undefined') console.log('x is undefined [typeof(x) === \'undefined\'].');
else console.log('x is not undefined [typeof(x) === \'undefined\'].');
// This will throw exception because what the hell is j? It is nowhere to be found.
try
{
if (j === undefined) console.log('j is undefined [j === undefined].');
else console.log('j is not undefined [j === undefined].');
}
catch(e){console.log('Error!!! Cannot use [j === undefined] because j is nowhere to be found in our source code.');}
// However this will not throw exception
if (typeof j === 'undefined') console.log('j is undefined (typeof(x) === \'undefined\'). We can use this check even though j is nowhere to be found in our source code and it will not throw.');
else console.log('j is not undefined [typeof(x) === \'undefined\'].');
};
If we call the above code like this:
f();
The output would be this:
x is undefined [x === undefined].
x is undefined [typeof(x) === 'undefined'].
Error!!! Cannot use [j === undefined] because j is nowhere to be found in our source code.
j is undefined (typeof(x) === 'undefined'). We can use this check even though j is nowhere to be found in our source code and it will not throw.
If we call the above code like these (with any value actually):
f(null);
f(1);
The output will be:
x is not undefined [x === undefined].
x is not undefined [typeof(x) === 'undefined'].
Error!!! Cannot use [j === undefined] because j is nowhere to be found in our source code.
j is undefined (typeof(x) === 'undefined'). We can use this check even though j is nowhere to be found in our source code and it will not throw.
When you do the check like this: typeof x === 'undefined', you are essentially asking this: Please check if the variable x exists (has been defined) somewhere in the source code. (more or less). If you know C# or Java, this type of check is never done because if it does not exist, it will not compile.
<== Fiddle Me ==>
Summary:
When at global scope we actually want to return true if the variable is not declared or has the value undefined:
var globalVar1;
// This variable is declared, but not defined and thus has the value undefined
console.log(globalVar1 === undefined);
// This variable is not declared and thus will throw a referenceError
console.log(globalVar2 === undefined);
Because in global scope we are not 100% sure if a variable is declared this might give us a referenceError. When we use the typeof operator on the unknown variable we are not getting this issue when the variable is not declared:
var globalVar1;
console.log(typeof globalVar1 === 'undefined');
console.log(typeof globalVar2 === 'undefined');
This is due to the fact that the typeof operator returns the string undefined when a variable is not declared or currently hold the value undefined which is exactly what we want.
With local variables we don't have this problem because we know beforehand that this variable will exist. We can simply look in the respective function if the variable is present.
With object properties we don't have this problem because when we try to lookup an object property which does not exist we also get the value undefined
var obj = {};
console.log(obj.myProp === undefined);
jQuery probably expects you to be using let and const variables in functions going forward, which in JavaScript's ES6 2015 design do NOT allow you to use any local scope (function) let or const variables until they are declared. Even hoisting by Javascript does not allow you to even type-check them!
If you try and do that, JavaScript generates an error, unlike with var variables which when hoisted creates a declared but uninitialized variable you can type check or check to see if its undefined.
If you declare a let or const variable in a function, but AFTER trying to access it, typeof checks still create a Reference Error in JavaScript! Its very odd behavior, and illogical to me why it was designed that way. But that is why jQuery likely sees no use for typeof function variable use. Example:
function MyError(){
// WOW! This variable DOES NOT EVEN EXIST, but you can still check its type!
if(typeof x === 'undefined')
{
alert(1);// OK!
}
// ERROR!
// WOW! You cannot even check an existing "let" variable's TYPE in a local function!
if(typeof y === 'undefined')//REFERENCE ERROR!!
{
alert(2);
}
// We defined the variable so its hoisted to the top but in a dead zone
let y = 'test';
}
MyError();
// RESULT
// alert 1 fires but a REFERENCE ERROR is generated from the second alert 2 condition.
It is odd above how a non-existing local variable cant be checked using typeof for 'undefined', but a declared let variable in the function cannot! So this is likely why I would not depend on jQuery to define what is best. There are edge cases.
More Weirdness on "undefined" variables in JavaScript
**undefined has two different expressions, and three different uses, as follows:
"typeof" and "undefined" types : Variables that are not declared and do not exist are not assigned anything, but have a "type" of undefined. If you access a variable that does NOT even exist, much less declared or initialized, you will generate a REFERENCE ERROR if you access it, even when testing for the primitive default value of undefined which is assigned to declared variables until assigned a value. So checking the "typeof" prevents this error in this one case as follows:
// In this first test, the variable "myVariable1" does not exist yet so creates
// an error if we try and check if its assigned the default value of undefined!
if (myVariable1 === undefined) alert(true);// REFERENCE ERROR!
// Here we can elegantly catch the "undefined" type
// of the missing variable and stop the REFERENCE ERROR using "typeof".
if (typeof myVariable1 === "undefined") alert(true);// true
// Here we have declared the missing variable and notice its
// still an "undefined" type until initialized with a value.
let myVariable1;
if (typeof myVariable1 === "undefined") alert(true);// true
// Lastly, after we assign a value, the type is no longer
// "undefined" so returns false.
myVariable1 = 'hello';
if (typeof myVariable1 === "undefined") alert(true);// false
All objects and types in JavaScript that are accessed but not declared will default to a type of "undefined". So, the lesson here is try and check for the typeof first, to prevent missing variable errors!
undefined primitive values : All declared variables not yet assigned a value are assigned in JavaScript the primitve of undefined. If you have declared a variable, but not initialized it yet, its assigned this default primitive type of undefined. That is not same as an "undefined" type. The primitive value of undefined is a reserved value but can be altered, but that's not what is asked here. Notice this catches all declared but uninitialized variables only:
let myVariable3;
if (myVariable3 === undefined) alert(true);// true
let myVariable4 = 'hello';
if (myVariable4 === undefined) alert(true);// false
Objects and undefined primitives : Lastly, Object properties do NOT behave like variables in JavaScript. Object properties, when missing do not become undefined types, but are simply assigned the primitive undefined as above for undeclared variables. So they act like #2:
let myObject = {};
if (myObject.myProperty === undefined) alert(true);// true
BEST PRACTICE
Lastly....this is a VERY GOOD REASON to always check for BOTH the "undefined" type and the undefined primitive value on variables in all your JavaScript code. Most will say, you will rarely need both. There may come a day when a missing variable is accessed in a library that does not exist and creates a nasty JavaScript REFERENCE ERROR! So I always do this check, and in this order, to stop all errors in JavaScript:
if (typeof myVariable !== "undefined" && myVariable !== undefined) {
// do something safe with myVariable!
}
typeof a === 'undefined' is faster then a === 'undefined' by about 2 times on node v6.9.1.