What is the benefit of angular.isdefined? - javascript

What is the benefit of angular.isdefined over and above foo === undefined?
I can't immediately think of a benefit.

Accessing a truly undefined variable in any way in Javascript, except typeof throws an error. You can only use Angular.isDefined with properties. E.g, this would work fine:
angular.isDefined(window.obj);
Because obj is an undefined propery of window.
Examples of the expected behavior:
var foo;
var bar = 42;
typeof foo !== 'undefined'; // false
typeof bar !== 'undefined'; // true
typeof baz !== 'undefined'; // false
angular.isDefined(foo); // false
angular.isDefined(bar); // true
angular.isDefined(baz); // ReferenceError

Here is the source:
function isDefined(value) {return typeof value !== 'undefined';}
Obviously the first reason is a lower verbosity, but it also future proofs angular, especially if the function is used internally.

Like Kamrul said angular does:
function isDefined(value) { return typeof value !== 'undefined'; }
Which means "the type of this var is undefined"... in you example you compare the content of the variable is equals to undefined and angular is checking the type of the variable.
In js the types are dynamic so until you don't assign a value the variable has no type... so isDefined will tell you both, if a variable declaration exist and if this variable has any content.
But, be careful because the variable could be null, in which case the type of the variable would be object.
You could try this code:
var a;
var b = 'asd';
var c = null;
console.log('a: ' + typeof a);
console.log('b: ' + typeof b);
console.log('c: ' + typeof c);
console.log('d: ' + typeof d);
And you will see the next in console:
a: undefined
b: string
c: object
d: undefined
So,
a) the var exist but has no value so is undefined
b) the var exist and has value.. this value is a string so this is its type
c) the var exist but is null, the type can't be interfered so its type is object
d) the var has not been declared so... it's undefined
The main point is the diference between "a" and "d"... so try the next:
console.log('a is undefined? ' + a === undefined);
console.log('d is undefined? ' + d === undefined);
You will see the next in console:
false
Uncaught ReferenceError: d is not defined
Which... is a big problem because:
a) tells you that is not undefined when that's not true
d) raise an exception so... you code will fail
Conclusion
Use is defined when you want to check if a variable exists and has been initialized with a value, but be careful with null values because null is an object (so is a defined var).
If you want to validate that a variable exists and has any valid value (so is not null) you can simple do something like:
if (myvar) {
console.log('myvar is defined and is not null');
} else {
console.log('myvar is undefined or null');
}
Another good trick is to init to some value if the var is not defined with ||
myvar = myvar || 'some init value';
The above code takes the value of myvar if is defined and not null and if not init it with some value.
As #TonyBrasunas put on his comment if myvar is evaluated to false, 'some init value' will be assigned. Take this into consideration before using this trick.
This is good in functions, for example:
function split(input, charToSplit) {
charToSplit = charToSplit || ' ';
return input.split(charToSplit);
}
Then by default you can split with whitespaces:
var input = 'asd asd';
var splited = split(input);
// --> splited = ['asd', 'asd']
Or... with another char:
var input = 'asd|asd';
var splited = split(input, '|');
// --> splited= ['asd', 'asd']

I can only guess but I think my guess is a pretty good one.
These two expressions are functionally equivalent:
typeof foo !== 'undefined'
angular.isDefined(foo)
Benefits of the latter include:
1) It's arguably less of a mental strain to ask whether something is defined than to ask if something is not undefined.
2) angular.isDefined(foo) is arguably a lot less "noisy" than typeof foo !== 'undefined', and therefore it's quicker to grasp what's happening.
Note: These aren't my arguments for the superiority of angular.isDefined. What I'm trying to convey is my guess as to why the Angular team wanted to create angular.isDefined and why they thought it was better than the plain JavaScript alternative.

Related

Undefined type in JavaScript

Sorry, I have a weird question; I know undefined is a type in JavaScript; is it possible to set the type of a variable to undefined?
This is a serious question for me although it seems weird.
It can be done in several ways:
Just declare a symbol:
var symbol;
Or declare a symbol and set it to undefined:
var symbol = undefined;
In case the undefined symbol was overridden:
var symbol = void 0;
Or
var symbol = (function(arg) { return arg; })();
Say your variable is named test:
delete test; // true
typeof(test); // "undefined"
This may not work with the strictest of linters or JavaScript runtime environments. This only works if the variable is in the global scope.
Accoding MDN documentation:
The global undefined property represents the primitive value undefined. It is one of JavaScript's primitive types.
Property attributes of undefined
Writable NO
Enumerable NO
Configurable NO
Ways to declare an undefined variable:
var foo;
var bar = undefined;
var baz = void 0;
var undefined = 2; // <= NO
console.log(foo); //undefined
console.log(bar); //undefined
console.log(baz); //undefined
console.log(undefined); //undefined
Mysteriously. Before you could declare the value to undefined, but now I try, and you can not. I guess now it is a reserved word.

Default value of a type in javascript

Is there a function in JavaScript that returns the default value for a type name that is passed to it? For example:
var defaultValue = built_in_getDefaultValue("number");
console.log(defaultValue); // Logs the number 0 to the console.
Both previous answers correctly note that the default (unassigned) value of a variable in JavaScript is undefined, but neither addresses what you seem to be looking for—an equivalent of e.g. the default operator in C#.
Fortunately, JavaScript has a very simple type system: everything that isn't one of the seven primitive types is an object and can be called via its constructor.¹ The following function, given a string representing
the name of a JS primitive type, e.g.'string' or 'null';
any valid production of the typeof operator, e.g. 'function';
a function name either in the this value it is called with or its local scope²
will produce a reasonable interpretation of a "default" value:
function defaultVal(type) {
if (typeof type !== 'string') throw new TypeError('Type must be a string.');
// Handle simple types (primitives and plain function/object)
switch (type) {
case 'bigint' : return BigInt(0);
case 'boolean' : return false;
case 'function' : return function () {};
case 'null' : return null;
case 'number' : return 0;
case 'object' : return {};
case 'string' : return "";
case 'symbol' : return Symbol();
case 'undefined' : return void 0;
}
try {
// Look for constructor in this or current scope
var ctor = typeof this[type] === 'function'
? this[type]
: eval(type);
return new ctor;
// Constructor not found, return new object
} catch (e) { return {}; }
}
You can call it like this:
defaultVal( typeof 1 ); // -> 0
defaultVal( 'bigint' ); // -> 0n
defaultVal( 'object' ); // -> {}
defaultVal( 'RegExp' ); // -> /(?:)/
Unfortunately, the JS typeof operator may be a bit… anameic for our purposes. For example, typeof null === 'object'¹, and typeof [] === 'object', which probably isn't what you want.
To work around this, here's a function that returns the result of calling typeof on a value unless the result is 'object', in which case it will return 'null' if the value is null and obj.constructor.name otherwise (with 'object' as the fallback value if all else fails):
function getType(obj) {
var type = typeof obj;
if (type !== 'object') return type; // primitive or function
if (obj === null) return 'null'; // null
// Everything else, check for a constructor
var ctor = obj.constructor;
var name = typeof ctor === 'function' && ctor.name;
return typeof name === 'string' && name.length > 0 ? name : 'object';
}
And now we can have:
defaultVal( getType( 1234 ) ); // -> 0
defaultVal( getType( [99] ) ); // -> []
defaultVal( getType( 'ab' ) ); // -> ""
defaultVal( getType( null ) ); // -> null (Not possible with typeof!)
defaultVal( getType( /.*/ ) ); // -> /(?:)/ (Not possible with typeof!)
function T () {}
defaultVal( getType( new T ) ); // -> T {} (Not possible with typeof!)
I suspect this is as close to what you're looking for as you're going to get. Also, to head off any criticism: the use of eval above might seem a bit dirty, but it's the only way to get a named value from the current scope.
¹ null is a bit of an oddity. The ECMAScript 2020 specification clearly refers to it as a primitive; however, typeof null is 'object' due to a bug in the original JavaScript implementation. At one point MDN excluded null from its list of primitives, counting only six primitives and stating that null should be considered a "special case for every Object".
Based on the spec, I refer to null as a primitive in this answer, and MDN has since been updated to agree with this stance.
² This function can't call a constructor instantiated in another scope; instead, I've made it possible to call it with this bound to an object containing any such constructors it may reference:
function innerScopeCtor() {
function T () {}
return defaultVal.call( { T : T }, 'T' );
}
innerScopeCtor(); // T {}
If you don't do this, it will just fall back to returning a new object.
I don't understand why do you ask such a question. Anyways, the default value of a variable in JavaScript is null or undefined.
For learning purposes, I took this from WikiBooks JavaScript/Variables and Types:
Variables are commonly explicitly declared by the var statement, as
shown below:
var c;
The above variable is created, but has the default value of undefined.
To be of value, the variable needs to be initialized:
var c = 0;
After being declared, a variable may be assigned a new value which
will replace the old one:
c = 1;
But make sure to declare a variable with var before (or while)
assigning to it; otherwise you will create a "scope bug."
And now, when you ask why the value is not 0, it is because, even null or undefined are values, which are not defined. Not defined is different from being defined and empty. It might return 0, when the value is declared and not defined.
The default value of any variable in javascript is undefined. You can also get it as
var defaultValue = void 0;

What is the difference between null and undefined in JavaScript?

I want to know what the difference is between null and undefined in JavaScript.
undefined means a variable has been declared but has not yet been assigned a value :
var testVar;
console.log(testVar); //shows undefined
console.log(typeof testVar); //shows undefined
null is an assignment value. It can be assigned to a variable as a representation of no value :
var testVar = null;
console.log(testVar); //shows null
console.log(typeof testVar); //shows object
From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.
Proof :
console.log(null === undefined) // false (not the same type)
console.log(null == undefined) // true (but the "same value")
console.log(null === null) // true (both type and value are the same)
and
null = 'value' // Uncaught SyntaxError: invalid assignment left-hand side
undefined = 'value' // 'value'
The difference can be explained with toilet tissue holder:
A non-zero value is like a holder with roll of toilet tissue and there's tissue still on the tube.
A zero value is like a holder with an empty toilet tissue tube.
A null value is like a holder that doesn't even have a tissue tube.
An undefined value is similar to the holder itself being missing.
I picked this from here
The undefined value is a primitive value used when a variable has not
been assigned a value.
The null value is a primitive value that represents the null, empty,
or non-existent reference.
When you declare a variable through var and do not give it a value, it will have the value undefined. By itself, if you try to WScript.Echo() or alert() this value, you won't see anything. However, if you append a blank string to it then suddenly it'll appear:
var s;
WScript.Echo(s);
WScript.Echo("" + s);
You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". This is a small difference indeed.
You can even compare a variable that is undefined to null or vice versa, and the condition will be true:
undefined == null
null == undefined
They are, however, considered to be two different types. While undefined is a type all to itself, null is considered to be a special object value. You can see this by using typeof() which returns a string representing the general type of a variable:
var a;
WScript.Echo(typeof(a));
var b = null;
WScript.Echo(typeof(b));
Running the above script will result in the following output:
undefined
object
Regardless of their being different types, they will still act the same if you try to access a member of either one, e.g. that is to say they will throw an exception. With WSH you will see the dreaded "'varname' is null or not an object" and that's if you're lucky (but that's a topic for another article).
You can explicitely set a variable to be undefined, but I highly advise against it. I recommend only setting variables to null and leave undefined the value for things you forgot to set. At the same time, I really encourage you to always set every variable. JavaScript has a scope chain different than that of C-style languages, easily confusing even veteran programmers, and setting variables to null is the best way to prevent bugs based on it.
Another instance where you will see undefined pop up is when using the delete operator. Those of us from a C-world might incorrectly interpret this as destroying an object, but it is not so. What this operation does is remove a subscript from an Array or a member from an Object. For Arrays it does not effect the length, but rather that subscript is now considered undefined.
var a = [ 'a', 'b', 'c' ];
delete a[1];
for (var i = 0; i < a.length; i++)
WScript.Echo((i+".) "+a[i]);
The result of the above script is:
0.) a
1.) undefined
2.) c
You will also get undefined returned when reading a subscript or member that never existed.
The difference between null and undefined is: JavaScript will never set anything to null, that's usually what we do. While we can set variables to undefined, we prefer null because it's not something that is ever done for us. When you're debugging this means that anything set to null is of your own doing and not JavaScript. Beyond that, these two special values are nearly equivalent.
Please read the following carefully. It should remove all your doubts regarding the difference between null and undefined in JavaScript. Also, you can use the utility function at the end of this answer to get more specific types of variables.
In JavaScript we can have the following types of variables:
Undeclared Variables
Declared but Unassigned Variables
Variables assigned with literal undefined
Variables assigned with literal null
Variables assigned with anything other than undefined or null
The following explains each of these cases one by one:
Undeclared Variables
Can only be checked with the typeof operator which returns string 'undefined'
Cannot be checked with the loose equality operator ( == undefined ), let alone the strict equality operator ( === undefined ),
as well as if-statements and ternary operators ( ? : ) — these throw Reference Errors
Declared but Unassigned Variables
typeof returns string 'undefined'
== check with null returns true
== check with undefined returns true
=== check with null returns false
=== check with undefined returns true
Is falsy to if-statements and ternary operators ( ? : )
Variables assigned with literal undefined
These variables are treated exactly the same as Declared But Unassigned Variables.
Variables assigned with literal null
typeof returns string 'object'
== check with null returns true
== check with undefined returns true
=== check with null returns true
=== check with undefined returns false
Is falsy to if-statements and ternary operators ( ? : )
Variables assigned with anything other than undefined or null
typeof returns one of the following strings: 'bigint', 'boolean', 'function', 'number', 'object', 'string', 'symbol'
Following provides the algorithm for correct type checking of a variable:
Get the typeof our variable and return it if it isn't 'object'
Check for null, as typeof null returns 'object' as well
Evaluate Object.prototype.toString.call(o) with a switch statement to return a more precise value. Object's toString method returns strings that look like '[object ConstructorName]' for native/host objects. For all other objects (user-defined objects), it always returns '[object Object]'
If that last part is the case (the stringified version of the variable being '[object Object]') and the parameter returnConstructorBoolean is true, it will try to get the name of the constructor by toString-ing it and extracting the name from there. If the constructor can't be reached, 'object' is returned as usual. If the string doesn't contain its name, 'anonymous' is returned
(supports all types up to ECMAScript 2020)
function TypeOf(o, returnConstructorBoolean) {
const type = typeof o
if (type !== 'object') return type
if (o === null) return 'null'
const toString = Object.prototype.toString.call(o)
switch (toString) {
// Value types: 6
case '[object BigInt]': return 'bigint'
case '[object Boolean]': return 'boolean'
case '[object Date]': return 'date'
case '[object Number]': return 'number'
case '[object String]': return 'string'
case '[object Symbol]': return 'symbol'
// Error types: 7
case '[object Error]': return 'error'
case '[object EvalError]': return 'evalerror'
case '[object RangeError]': return 'rangeerror'
case '[object ReferenceError]': return 'referenceerror'
case '[object SyntaxError]': return 'syntaxerror'
case '[object TypeError]': return 'typeerror'
case '[object URIError]': return 'urierror'
// Indexed Collection and Helper types: 13
case '[object Array]': return 'array'
case '[object Int8Array]': return 'int8array'
case '[object Uint8Array]': return 'uint8array'
case '[object Uint8ClampedArray]': return 'uint8clampedarray'
case '[object Int16Array]': return 'int16array'
case '[object Uint16Array]': return 'uint16array'
case '[object Int32Array]': return 'int32array'
case '[object Uint32Array]': return 'uint32array'
case '[object Float32Array]': return 'float32array'
case '[object Float64Array]': return 'float64array'
case '[object ArrayBuffer]': return 'arraybuffer'
case '[object SharedArrayBuffer]': return 'sharedarraybuffer'
case '[object DataView]': return 'dataview'
// Keyed Collection types: 2
case '[object Map]': return 'map'
case '[object WeakMap]': return 'weakmap'
// Set types: 2
case '[object Set]': return 'set'
case '[object WeakSet]': return 'weakset'
// Operation types: 3
case '[object RegExp]': return 'regexp'
case '[object Proxy]': return 'proxy'
case '[object Promise]': return 'promise'
// Plain objects
case '[object Object]':
if (!returnConstructorBoolean)
return type
const _prototype = Object.getPrototypeOf(o)
if (!_prototype)
return type
const _constructor = _prototype.constructor
if (!_constructor)
return type
const matches = Function.prototype.toString.call(_constructor).match(/^function\s*([^\s(]+)/)
return matches ? matches[1] : 'anonymous'
default: return toString.split(' ')[1].slice(0, -1)
}
}
null is a special keyword that indicates an absence of value.
think about it as a value, like:
"foo" is string,
true is boolean ,
1234 is number,
null is undefined.
undefined property indicates that a variable has not been assigned a value including null too .
Like
var foo;
defined empty variable is null of datatype undefined
Both of them are representing a value of a variable with no value
AND
null doesn't represent a string that has no value - empty string-
Like
var a = '';
console.log(typeof a); // string
console.log(a == null); //false
console.log(a == undefined); // false
Now if
var a;
console.log(a == null); //true
console.log(a == undefined); //true
BUT
var a;
console.log(a === null); //false
console.log(a === undefined); // true
SO each one has it own way to use
undefined use it to compare the variable data type
null use it to empty a value of a variable
var a = 'javascript';
a = null ; // will change the type of variable "a" from string to object
null: absence of value for a variable; undefined: absence of variable itself;
..where variable is a symbolic name associated with a value.
JS could be kind enough to implicitly init newly declared variables with null, but it does not.
You might consider undefined to represent a system-level, unexpected, or error-like absence of value and null to represent program-level, normal, or expected absence of value.
via JavaScript:The Definitive Guide
The best way to understand the difference is to first clear your mind of the inner workings of JavaScript and just understand the differences in meaning between:
let supervisor = "None"
// I have a supervisor named "None"
let supervisor = null
// I do NOT have a supervisor. It is a FACT that I do not.
let supervisor = undefined
// I may or may not have a supervisor. I either don't know
// if I do or not, or I am choosing not to tell you. It is
// irrelevant or none of your business.
There is a difference in meaning between these three cases, and JavaScript distinguishes the latter two cases with two different values, null and undefined. You are free to use those values explicitly to convey those meanings.
So what are some of the JavaScript-specific issues that arise due to this philosophical basis?
A declared variable without an initializer gets the value undefined because you never said anything about the what the intended value was.
let supervisor;
assert(supervisor === undefined);
A property of an object that has never been set evaluates to undefined because no one ever said anything about that property.
const dog = { name: 'Sparky', age: 2 };
assert(dog.breed === undefined);
null and undefined are "similar" to each other because Brendan Eich said so. But they are emphatically not equal to each other.
assert(null == undefined);
assert(null !== undefined);
null and undefined thankfully have different types. null belongs to the type Null and undefined to the type Undefined. This is in the spec, but you would never know this because of the typeof weirdness which I will not repeat here.
A function reaching the end of its body without an explicit return statement returns undefined since you don't know anything about what it returned.
By the way, there are other forms of "nothingness" in JavaScript (it's good to have studied Philosophy....)
NaN
Using a variable that has never been declared and receiving a ReferenceError
Using a let or const defined local variable in its temporal dead zone and receiving a ReferenceError
Empty cells in sparse arrays. Yes these are not even undefined although they compare === to undefined.
$ node
> const a = [1, undefined, 2]
> const b = [1, , 2]
> a
[ 1, undefined, 2 ]
> b
[ 1, <1 empty item>, 2 ]
A lot of "technical" answers have been given, all of them mostly correct from the limited point of view of JS as a mere programming language.
However, I would like to add the following thoughts, especially when you're writing TypeScript code as part of a bigger project / (enterprise) application:
When talking with a Backend of some kind you'll most probably receive JSON
While some backends correctly avoid the use of "null" in their JSON (removing those properties), others do not
Now, while "null" may mean that the value is missing deliberately, more often it does not convey this meaning. Most databases use "null" just because they don't have an "undefined" type. But the meaning really just is "undefined".
Because of that, you can never know if a "null" value really means deliberate absence. Therefore "null" cannot really mean the deliberate choice of "missing value". It is undecidable in general.
As a consequence, semantically, "null" and "undefined" are exactly the same thing in practice.
Therefore, in an effort to harmonize things I'm strictly against using "null" and want to encourage you to stop using "null" in your code. It's far easier than you might think. Don't get me wrong. I'm not talking about not handling "null" values, only to avoid explicitly using them in your code. Put differently: your code should still be able to work with accidentally passed "null" values coming from outside your application, e.g. via a 3rd party lib like Angular, or a 3rd party backend.
Here are the guidelines that make it possible:
avoid direct undefined type guards (e.g. if (value === undefined) { ... }.
Instead, use indirect type guards (aka truthiness checks) e.g. if (value) { ... }
Whenever 0 or empty strings are meaningful, use either
an explicit helper method like Lodash's isNil
or include the meaningful value in the comparison (e.g. if (!value && value !== 0) { ... })
Consider using a lint rule that disallows the usage of null
null is a special value meaning "no value". null is a special object because typeof null returns 'object'.
On the other hand, undefined means that the variable has not been declared, or has not been given a value.
I'll explain undefined, null and Uncaught ReferenceError:
1 - Uncaught ReferenceError : variable has not been declared in your script, there is no reference to this varaible
2 - undefined: Variable declared but does not initialised
3 - null : Variable declared and is an empty value
null and undefined are two distinct object types which have the following in common:
both can only hold a single value, null and undefined respectively;
both have no properties or methods and an attempt to read any properties of either will result in a run-time error (for all other objects, you get value undefined if you try to read a non-existent property);
values null and undefined are considered equal to each other and to nothing else by == and != operators.
The similarities however end here. For once, there is a fundamental difference in the way how keywords null and undefined are implemented. This is not obvious, but consider the following example:
var undefined = "foo";
WScript.Echo(undefined); // This will print: foo
undefined, NaN and Infinity are just names of preinitialized "superglobal" variables - they are initialized at run-time and can be overridden by normal global or local variable with the same names.
Now, let's try the same thing with null:
var null = "foo"; // This will cause a compile-time error
WScript.Echo(null);
Oops! null, true and false are reserved keywords - compiler won't let you use them as variable or property names
Another difference is that undefined is a primitive type, while null is an object type (indicating the absense of an object reference). Consider the following:
WScript.Echo(typeof false); // Will print: boolean
WScript.Echo(typeof 0); // Will print: number
WScript.Echo(typeof ""); // Will print: string
WScript.Echo(typeof {}); // Will print: object
WScript.Echo(typeof undefined); // Will print: undefined
WScript.Echo(typeof null); // (!!!) Will print: object
Also, there is an important difference in the way null and undefined are treated in numeric context:
var a; // declared but uninitialized variables hold the value undefined
WScript.Echo(a === undefined); // Prints: -1
var b = null; // the value null must be explicitly assigned
WScript.Echo(b === null); // Prints: -1
WScript.Echo(a == b); // Prints: -1 (as expected)
WScript.Echo(a >= b); // Prints: 0 (WTF!?)
WScript.Echo(a >= a); // Prints: 0 (!!!???)
WScript.Echo(isNaN(a)); // Prints: -1 (a evaluates to NaN!)
WScript.Echo(1*a); // Prints: -1.#IND (in Echo output this means NaN)
WScript.Echo(b >= b); // Prints: -1 (as expected)
WScript.Echo(isNaN(b)); // Prints: 0 (b evaluates to a valid number)
WScript.Echo(1*b); // Prints: 0 (b evaluates to 0)
WScript.Echo(a >= 0 && a <= 0); // Prints: 0 (as expected)
WScript.Echo(a == 0); // Prints: 0 (as expected)
WScript.Echo(b >= 0 && b <= 0); // Prints: -1 (as expected)
WScript.Echo(b == 0); // Prints: 0 (!!!)
null becomes 0 when used in arithmetic expressions or numeric comparisons - similarly to false, it is basically just a special kind of "zero". undefined, on the other hand, is a true "nothing" and becomes NaN ("not a number") when you try to use it in numeric context.
Note that null and undefined receive a special treatment from == and != operators, but you can test true numeric equality of a and b with the expression (a >= b && a <= b).
Undefined means a variable has been declared but has no value:
var var1;
alert(var1); //undefined
alert(typeof var1); //undefined
Null is an assignment:
var var2= null;
alert(var2); //null
alert(typeof var2); //object
tl;dr
Use null for set a variable you know it is an Object.
Use undefined for set a variable whose type is mixed.
This is my usage of both 5 primitives and Object type, and that explain the difference between « use case » of undefined or null.
String
If you know a variable is only a string while all lifecycle, by convention, you could initialize it, to "":
("") ? true : false; // false
typeof ""; // "string";
("Hello World") ? true : false; // true
typeof "Hello World"; // "string"
Number
If you know a variable is only a number while all lifecycle, by convention, you could initialize it, to 0 (or NaN if 0 is an important value in your usage):
(0) ? true : false; // false
typeof 0; // "number";
(16) ? true : false; // true
typeof 16; // "number"
or
(NaN) ? true : false; // false
typeof NaN; // "number";
(16) ? true : false; // true
typeof 16; // "number"
Boolean
If you know a variable is only a boolean while all lifecycle, by convention, you could initialize it, to false:
(false) ? true : false; // false
typeof false; // "boolean";
(true) ? true : false; // true
typeof true; // "boolean"
Object
If you know a variable is only an Object while all lifecycle, by convention, you could initialize it, to null:
(null) ? true : false; // false
typeof null; // "object";
({}) ? true : false; // true
typeof {}; // "object"
Note: the smart usage off null is to be the falsy version of an Object because an Object is always true, and because typeof null return object. That means typeof myVarObject return consistent value for both Object and null type.
All
If you know a variable has a mixed type (any type while all lifecycle), by convention, you could initialize it, to undefined.
In addition to a different meaning there are other differences:
Object destructuring works differently for these two values:
const { a = "default" } = { a: undefined }; // a is "default"
const { b = "default" } = { b: null }; // b is null
JSON.stringify() keeps null but omits undefined
const json = JSON.stringify({ undefinedValue: undefined, nullValue: null });
console.log(json); // prints {"nullValue":null}
typeof operator
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" instead of "null"
In JavasScript there are 5 primitive data types: String, Number, Boolean, null and undefined.
I will try to explain with some simple examples.
Let's say we have a simple function
function test(a) {
if(a == null) {
alert("a is null");
} else {
alert("The value of a is " + a);
}
}
Also, in above function if(a == null) is the same as if(!a).
Now when we call this function without passing the parameter a
test(); // will alert "a is null";
test(4); // will alert "The value of a is " + 4;
also
var a;
alert(typeof a);
This will give undefined; we have declared a variable but we have not asigned any value to this variable;
but if we write
var a = null;
alert(typeof a); // will give alert as object
so null is an object. In a way we have assigned a value null to 'a'
When you declare a variable in javascript, it is assigned the value undefined. This means the variable is untouched and can be assigned any value in future. It also implies that you don't know the value that this variable is going to hold at the time of declaration.
Now you can explicitly assign a variable null. It means that the variable does not have any value. For example - Some people don't have a middle name. So in such a case its better to assign the value null to the middlename variable of a person object.
Now suppose that someone is accessing the middlename variable of your person object and it has the value undefined. He wouldn't know if the developer forgot to initialize this variable or if it didn't have any value. If it has the value null, then the user can easily infer that middlename doesn't have any value and it is not an untouched variable.
OK, we may get confused when we hear about null and undefined, but let's start it simple, they both are falsy and similar in many ways, but weird part of JavaScript, make them a couple of significant differences, for example, typeof null is 'object' while typeof undefined is 'undefined'.
typeof null; //"object"
typeof undefined; //"undefined";
But if you check them with == as below, you see they are both falsy:
null==undefined; //true
Also you can assign null to an object property or to a primitive, while undefined can simply be achieved by not assigning to anything.
I create a quick image to show the differences for you at a glance.
For the undefined type, there is one and only one value: undefined.
For the null type, there is one and only one value: null.
So for both of them, the label is both its type and its value.
The difference between them. For example:
null is an empty value
undefined is a missing value
Or:
undefined hasn't had a value yet
null had a value and doesn't anymore
Actually, null is a special keyword, not an identifier, and thus you cannot treat it as a variable to assign to.
However, undefined is an identifier. In both non-strict mode and strict mode, however, you can create a local variable of the name undefined. But this is one terrible idea!
function foo() {
undefined = 2; // bad idea!
}
foo();
function foo() {
"use strict";
undefined = 2; // TypeError!
}
foo();
I want to add a knowledge point which pertains to a subtle difference between null and undefined. This is good to know when you are trying to learn Vanilla JavaScript(JS) from ground up:
null is a reserved keyword in JS while undefined is a property on
the global object of the run-time environment you're in.
While writing code, this difference is not identifiable as both null and undefined are always used in right hand side (RHS) of a JavaScript statement. But when you use them in left hand side (LHS) of an expression then you can observe this difference easily. So JS interpreter interprets the below code as error:
var null = 'foo'
It gives below error:
Uncaught SyntaxError: Unexpected token null
At the same time, below code runs successfully although I won't recommend doing so in real life:
var undefined = 'bar'
This works because undefined is a property on the global object (window object in case of JavaScript running in a browser)
null and undefined are both are used to represent the absence of some value.
var a = null;
a is initialized and defined.
typeof(a)
//object
null is an object in JavaScript
Object.prototype.toString.call(a) // [object Object]
var b;
b is undefined and uninitialized
undefined object properties are also undefined. For example "x" is not defined on object c and if you try to access c.x, it will return undefined.
Generally we assign null to variables not undefined.
Per Ryan Morr's thorough article on this subject...
"Generally, if you need to assign a non-value to a variable or property, pass it to a function, or return it from a function, null is almost always the best option. To put it simply, JavaScript uses undefined and programmers should use null."
See Exploring the Eternal Abyss of Null and Undefined
In javascript all variables are stored as key value pairs. Each variable is stored as variable_name : variable_value/reference.
undefined means a variable has been given a space in memory, but no value is assigned to it. As a best practice, you should not use this type as an assignment.
In that case how to denote when you want a variable to be without value at a later point in the code? You can use the type
null ,which is also a type that is used to define the same thing, absence of a value, but it is not the same as undefined, as in this case you actually have the value in memory. That value is null
Both are similar but usage and meaning are different.
The difference in meaning between undefined and null is an accident of JavaScript’s design, and it doesn’t matter most of the time. In cases where you actually have to concern yourself with these values, I recommend treating them as mostly interchangeable.
From the Eloquent Javascript book
As typeof returns undefined, undefined is a type where as null is an initializer indicates the variable points to no object(virtually everything in Javascript is an object).
null - It is an assignment value, which is used with variable to represent no value (it's an object).
undefined - It is a variable which does not have any value assigned to it, so JavaScript will assign an undefined to it (it's a data type).
undeclared - If a variable is not created at all, it is known as undeclared.
Check this out. The output is worth thousand words.
var b1 = document.getElementById("b1");
checkif("1, no argument" );
checkif("2, undefined explicitly", undefined);
checkif("3, null explicitly", null);
checkif("4, the 0", 0);
checkif("5, empty string", '');
checkif("6, string", "string");
checkif("7, number", 123456);
function checkif (a1, a2) {
print("\ncheckif(), " + a1 + ":");
if (a2 == undefined) {
print("==undefined: YES");
} else {
print("==undefined: NO");
}
if (a2 === undefined) {
print("===undefined: YES");
} else {
print("===undefined: NO");
}
if (a2 == null) {
print("==null: YES");
} else {
print("==null: NO");
}
if (a2 === null) {
print("===null: YES");
} else {
print("===null: NO");
}
if (a2 == '') {
print("=='': YES");
} else {
print("=='': NO");
}
if (a2 === '') {
print("==='': YES");
} else {
print("==='': NO");
}
if (isNaN(a2)) {
print("isNaN(): YES");
} else {
print("isNaN(): NO");
}
if (a2) {
print("if-?: YES");
} else {
print("if-?: NO");
}
print("typeof(): " + typeof(a2));
}
function print(v) {
b1.innerHTML += v + "\n";
}
<!DOCTYPE html>
<html>
<body>
<pre id="b1"></pre>
</body>
</html>
See also:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
Cheers!
The difference between undefined and null is minimal, but there is a difference. A variable whose value is undefined has never been initialized. A variable whose value is null was explicitly given a value of null, which means that the variable was explicitly set to have no value. If you compare undefined and null by using the null==undefined expression, they will be equal.
Basically, Undefined is a global variable that javascript create at the run time whether null means that no value has assigned to the variable (actually null is itself an object).
Let's take an example:
var x; //we declared a variable x, but no value has been assigned to it.
document.write(x) //let's print the variable x
Undefined that's what you will get as output.
Now,
x=5;
y=null;
z=x+y;
and you will get 5 as output. That's the main difference between the Undefined and null
Both special values imply an empty state.
The main difference is that undefined represents the value of a variable that wasn’t yet initialized, while null represents an intentional absence of an object.
The variable number is defined, however, is not assigned with an initial value:
let number;
number; // => undefined
number variable is undefined, which clearly indicates an uninitialized variable
The same uninitialized concept happens when a non-existing object property is accessed:
const obj = { firstName: 'Dmitri' };
obj.lastName; // => undefined
Because lastName property does not exist in obj, JavaScript correctly evaluates obj.lastName to undefined.
In other cases, you know that a variable expects to hold an object or a function to return an object. But for some reason, you can’t instantiate the object. In such a case null is a meaningful indicator of a missing object.
For example, clone() is a function that clones a plain JavaScript object. The function is expected to return an object:
function clone(obj) {
if (typeof obj === 'object' && obj !== null) {
return Object.assign({}, obj);
}
return null;
}
clone({name: 'John'}); // => {name: 'John'}
clone(15); // => null
clone(null); // => null
However, clone() might be invoked with a non-object argument: 15 or null (or generally a primitive value, null or undefined). In such case, the function cannot create a clone, so it returns null - the indicator of a missing object.
typeof operator makes the distinction between the two values:
typeof undefined; // => 'undefined'
typeof null; // => 'object'
The strict quality operator === correctly differentiates undefined from null:
let nothing = undefined;
let missingObject = null;
nothing === missingObject; // => false

typeof !== "undefined" vs. != null

I often see JavaScript code which checks for undefined parameters etc. this way:
if (typeof input !== "undefined") {
// do stuff
}
This seems kind of wasteful, since it involves both a type lookup and a string comparison, not to mention its verbosity. It's needed because undefined could be renamed, though.
My question is:
How is that code any better than this approach:
if (null != input) {
// do stuff
}
As far as I know, you can't redefine null, so it's not going to break unexpectedly. And, because of the type-coercion of the != operator, this checks for both undefined and null... which is often exactly what you want (e.g. for optional function parameters).
Yet this form does not seem widespread, and it even causes JSLint to yell at you for using the evil != operator.
Why is this considered bad style?
typeof is safer as it allows the identifier to never have been declared before:
if(typeof neverDeclared === "undefined") // no errors
if(neverDeclared === null) // throws ReferenceError: neverDeclared is not defined
If the variable is declared (either with the var keyword, as a function argument, or as a global variable), I think the best way to do it is:
if (my_variable === undefined)
jQuery does it, so it's good enough for me :-)
Otherwise, you'll have to use typeof to avoid a ReferenceError.
If you expect undefined to be redefined, you could wrap your code like this:
(function(undefined){
// undefined is now what it's supposed to be
})();
Or obtain it via the void operator:
const undefined = void 0;
// also safe
good way:
if(typeof neverDeclared == "undefined") //no errors
But the best looking way is to check via :
if(typeof neverDeclared === typeof undefined) //also no errors and no strings
You shouldn't really worry about undefined being renamed. If someone renames undefined, you will be in a lot more trouble than just a few if checks failing. If you really want to protect your code, wrap it in an IFFE (immediately invoked function expression) like this:
(function($, Backbone, _, undefined) {
//undefined is undefined here.
})(jQuery, Backbone, _);
If you're working with global variables (which is wrong already) in a browser enviroment, I'd check for undefined like this:
if(window.neverDefined === undefined) {
//Code works
}
Since global variables are a part of the window object, you can simply check against undefined instead of casting to a string and comparing strings.
On top of that, why are your variables not defined? I've seen a lot of code where they check a variables existence and perform some action based on that. Not once have I seen where this approach has been correct.
If you are really worried about undefined being redefined, you can protect against this with some helper method like this:
function is_undefined(value) {
var undefined_check; // instantiate a new variable which gets initialized to the real undefined value
return value === undefined_check;
}
This works because when someone writes undefined = "foo" he only lets the name undefined reference to a new value, but he doesn't change the actual value of undefined.
You can also use the void operator to obtain an undefined value:
if (input !== void 0) {
// do stuff
}
(And yes, as noted in another answer, this will throw an error if the variable was not declared, but this case can often be ruled out either by code inspection, or by code refactoring, e.g. using window.input !== void 0 for testing global variables or adding var input.)
I've actually come across if (typeof input !== 'undefined') in this scenario where it's being used to provide default function parameters:
function greet(name, greeting) {
name = (typeof name !== 'undefined') ? name : 'Student';
greeting = (typeof greeting !== 'undefined') ? greeting : 'Welcome';
return `${greeting} ${name}!`;
}
greet(); // Welcome Student!
greet('James'); // Welcome James!
greet('Richard', 'Howdy'); // Howdy Richard!
ES6 provides new ways of introducing default function parameters this way:
function greet(name = 'Student', greeting = 'Welcome') {
return `${greeting} ${name}!`;
}
greet(); // Welcome Student!
greet('James'); // Welcome James!
greet('Richard', 'Howdy'); // Howdy Richard!
This is less verbose and cleaner than the first option.
function greet(name, greeting) {
name = (typeof name !== 'undefined') ? name : 'Student';
greeting = (typeof greeting !== 'undefined') ? greeting : 'Welcome';
console.log(greeting,name);
}
greet(); // Welcome Student!
greet('James'); // Welcome James!
greet('Richard', 'Howdy'); // Howdy Richard!
//ES6 provides new ways of introducing default function parameters this way:
function greet2(name = 'Student', greeting = 'Welcome') {
// return '${greeting} ${name}!';
console.log(greeting,name);
}
greet2(); // Welcome Student!
greet2('James'); // Welcome James!
greet2('Richard', 'Howdy'); // Howdy Richard!
(function(){
var a= b = 3;
var ed = 103;
})();
//console.log(ed); //ed is not defined
console.log("a defined? " + (typeof a !== 'undefined')); //no define
console.log("b defined? " + (typeof b !== 'undefined')); //yes define
console.log(typeof(b)); //number
console.log(typeof(4+7)); //number
console.log(b); //3
console.log(typeof("4"+"7")); //string
var e= "ggg";
console.log(typeof(e)); //string
var ty=typeof(b);
console.log(ty); //number
console.log(typeof false); //boolean
console.log(typeof 1); //number
console.log(typeof 0); //number
console.log(typeof true); //boolean
console.log(typeof Math.tan); //function
console.log(typeof function(){}); //function
if(typeof neverDeclared == "undefined") //no errors
if(typeof neverDeclared === "undefined") //no errors
//if(neverDeclared == null) //showing error
console.log(typeof {a:1}); //object
console.log(typeof null); //object
console.log(typeof JSON); //object
console.log(typeof Math); //object
console.log(typeof /a-z/); //object
console.log(typeof new Date()); //object
console.log(typeof afbc); //undefined
//console.log(typeof new);//error
document.write("<br> * oprator as math ");
var r=14*"4";
document.write(r);
document.write("<br> + oprator as string ");
var r=14+"44";
document.write(r);
document.write("<br> Minus Operator work as mathematic ");
var r=64-"44";
document.write(r);
document.write("<br>");
console.log(typeof(4*"7")); //returns number
console.log(typeof(4+"7")); //returns string
Interview Question in JavaScript
var bar = null;
console.log(typeof bar === "object"); //true yes
//because null a datatype of object
var barf = "dff";
console.log(typeof barf.constructor);//function
console.log(Array.isArray(bar));//falsss
console.log((bar !== null) && (bar.constructor === Object)); //false
console.log((bar !== null) && (typeof bar === "object")); // logs false
//because bar!==null, bar is a object
console.log((bar !== null) && ((typeof bar === "object") || (typeof bar === "function"))); //false
console.log(typeof bar === typeof object); //false
console.log(typeof bar2 === typeof undefined); //true
console.log(typeof bar3 === typeof undefinedff); //true
console.log(typeof bar2 == typeof undefined); //true
console.log((bar !== null) && (typeof bar === "object") && (toString.call(bar) !== "[object Array]")); //false
if (input == undefined) { ... }
works just fine. It is of course not a null comparison, but I usually find that if I need to distinguish between undefined and null, I actually rather need to distinguish between undefined and just any false value, so
else if (input) { ... }
does it.
If a program redefines undefined it is really braindead anyway.
The only reason I can think of was for IE4 compatibility, it did not understand the undefined keyword (which is not actually a keyword, unfortunately), but of course values could be undefined, so you had to have this:
var undefined;
and the comparison above would work just fine.
In your second example, you probably need double parentheses to make lint happy?

Detecting an undefined object property

How do I check if an object property in JavaScript is undefined?
The usual way to check if the value of a property is the special value undefined, is:
if(o.myProperty === undefined) {
alert("myProperty value is the special value `undefined`");
}
To check if an object does not actually have such a property, and will therefore return undefined by default when you try to access it:
if(!o.hasOwnProperty('myProperty')) {
alert("myProperty does not exist");
}
To check if the value associated with an identifier is the special value undefined, or if that identifier has not been declared:
if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}
Note: this last method is the only way to refer to an undeclared identifier without an early error, which is different from having a value of undefined.
In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check foo === undefined might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.
However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.
If you are worried about this (unlikely) edge case, you can use the void operator to get at the special undefined value itself:
if(myVariable === void 0) {
alert("myVariable is the special value `undefined`");
}
I believe there are a number of incorrect answers to this topic. Contrary to common belief, "undefined" is not a keyword in JavaScript and can in fact have a value assigned to it.
Correct Code
The most robust way to perform this test is:
if (typeof myVar === "undefined")
This will always return the correct result, and even handles the situation where myVar is not declared.
Degenerate code. DO NOT USE.
var undefined = false; // Shockingly, this is completely legal!
if (myVar === undefined) {
alert("You have been misled. Run away!");
}
Additionally, myVar === undefined will raise an error in the situation where myVar is undeclared.
Many answers here are vehement in recommending typeof, but typeof is a bad choice. It should never be used for checking whether variables have the value undefined, because it acts as a combined check for the value undefined and for whether a variable exists. In the vast majority of cases, you know when a variable exists, and typeof will just introduce the potential for a silent failure if you make a typo in the variable name or in the string literal 'undefined'.
var snapshot = …;
if (typeof snaposhot === 'undefined') {
// ^
// misspelled¹ – this will never run, but it won’t throw an error!
}
var foo = …;
if (typeof foo === 'undefned') {
// ^
// misspelled – this will never run, but it won’t throw an error!
}
So unless you’re doing feature detection², where there’s uncertainty whether a given name will be in scope (like checking typeof module !== 'undefined' as a step in code specific to a CommonJS environment), typeof is a harmful choice when used on a variable, and the correct option is to compare the value directly:
var foo = …;
if (foo === undefined) {
⋮
}
Some common misconceptions about this include:
that reading an “uninitialized” variable (var foo) or parameter (function bar(foo) { … }, called as bar()) will fail. This is simply not true – variables without explicit initialization and parameters that weren’t given values always become undefined, and are always in scope.
that undefined can be overwritten. It’s true that undefined isn’t a keyword, but it is read-only and non-configurable. There are other built-ins you probably don’t avoid despite their non-keyword status (Object, Math, NaN…) and practical code usually isn’t written in an actively malicious environment, so this isn’t a good reason to be worried about undefined. (But if you are writing a code generator, feel free to use void 0.)
With how variables work out of the way, it’s time to address the actual question: object properties. There is no reason to ever use typeof for object properties. The earlier exception regarding feature detection doesn’t apply here – typeof only has special behaviour on variables, and expressions that reference object properties are not variables.
This:
if (typeof foo.bar === 'undefined') {
⋮
}
is always exactly equivalent to this³:
if (foo.bar === undefined) {
⋮
}
and taking into account the advice above, to avoid confusing readers as to why you’re using typeof, because it makes the most sense to use === to check for equality, because it could be refactored to checking a variable’s value later, and because it just plain looks better, you should always use === undefined³ here as well.
Something else to consider when it comes to object properties is whether you really want to check for undefined at all. A given property name can be absent on an object (producing the value undefined when read), present on the object itself with the value undefined, present on the object’s prototype with the value undefined, or present on either of those with a non-undefined value. 'key' in obj will tell you whether a key is anywhere on an object’s prototype chain, and Object.prototype.hasOwnProperty.call(obj, 'key') will tell you whether it’s directly on the object. I won’t go into detail in this answer about prototypes and using objects as string-keyed maps, though, because it’s mostly intended to counter all the bad advice in other answers irrespective of the possible interpretations of the original question. Read up on object prototypes on MDN for more!
¹ unusual choice of example variable name? this is real dead code from the NoScript extension for Firefox.
² don’t assume that not knowing what’s in scope is okay in general, though. bonus vulnerability caused by abuse of dynamic scope: Project Zero 1225
³ once again assuming an ES5+ environment and that undefined refers to the undefined property of the global object.
In JavaScript there is null and there is undefined. They have different meanings.
undefined means that the variable value has not been defined; it is not known what the value is.
null means that the variable value is defined and set to null (has no value).
Marijn Haverbeke states, in his free, online book "Eloquent JavaScript" (emphasis mine):
There is also a similar value, null, whose meaning is 'this value is defined, but it does not have a value'. The difference in meaning between undefined and null is mostly academic, and usually not very interesting. In practical programs, it is often necessary to check whether something 'has a value'. In these cases, the expression something == undefined may be used, because, even though they are not exactly the same value, null == undefined will produce true.
So, I guess the best way to check if something was undefined would be:
if (something == undefined)
Object properties should work the same way.
var person = {
name: "John",
age: 28,
sex: "male"
};
alert(person.name); // "John"
alert(person.fakeVariable); // undefined
What does this mean: "undefined object property"?
Actually it can mean two quite different things! First, it can mean the property that has never been defined in the object and, second, it can mean the property that has an undefined value. Let's look at this code:
var o = { a: undefined }
Is o.a undefined? Yes! Its value is undefined. Is o.b undefined? Sure! There is no property 'b' at all! OK, see now how different approaches behave in both situations:
typeof o.a == 'undefined' // true
typeof o.b == 'undefined' // true
o.a === undefined // true
o.b === undefined // true
'a' in o // true
'b' in o // false
We can clearly see that typeof obj.prop == 'undefined' and obj.prop === undefined are equivalent, and they do not distinguish those different situations. And 'prop' in obj can detect the situation when a property hasn't been defined at all and doesn't pay attention to the property value which may be undefined.
So what to do?
1) You want to know if a property is undefined by either the first or second meaning (the most typical situation).
obj.prop === undefined // IMHO, see "final fight" below
2) You want to just know if object has some property and don't care about its value.
'prop' in obj
Notes:
You can't check an object and its property at the same time. For example, this x.a === undefined or this typeof x.a == 'undefined' raises ReferenceError: x is not defined if x is not defined.
Variable undefined is a global variable (so actually it is window.undefined in browsers). It has been supported since ECMAScript 1st Edition and since ECMAScript 5 it is read only. So in modern browsers it can't be redefined to true as many authors love to frighten us with, but this is still a true for older browsers.
Final fight: obj.prop === undefined vs typeof obj.prop == 'undefined'
Pluses of obj.prop === undefined:
It's a bit shorter and looks a bit prettier
The JavaScript engine will give you an error if you have misspelled undefined
Minuses of obj.prop === undefined:
undefined can be overridden in old browsers
Pluses of typeof obj.prop == 'undefined':
It is really universal! It works in new and old browsers.
Minuses of typeof obj.prop == 'undefined':
'undefned' (misspelled) here is just a string constant, so the JavaScript engine can't help you if you have misspelled it like I just did.
Update (for server-side JavaScript):
Node.js supports the global variable undefined as global.undefined (it can also be used without the 'global' prefix). I don't know about other implementations of server-side JavaScript.
The issue boils down to three cases:
The object has the property and its value is not undefined.
The object has the property and its value is undefined.
The object does not have the property.
This tells us something I consider important:
There is a difference between an undefined member and a defined member with an undefined value.
But unhappily typeof obj.foo does not tell us which of the three cases we have. However we can combine this with "foo" in obj to distinguish the cases.
| typeof obj.x === 'undefined' | !("x" in obj)
1. { x:1 } | false | false
2. { x : (function(){})() } | true | false
3. {} | true | true
Its worth noting that these tests are the same for null entries too
| typeof obj.x === 'undefined' | !("x" in obj)
{ x:null } | false | false
I'd argue that in some cases it makes more sense (and is clearer) to check whether the property is there, than checking whether it is undefined, and the only case where this check will be different is case 2, the rare case of an actual entry in the object with an undefined value.
For example: I've just been refactoring a bunch of code that had a bunch of checks whether an object had a given property.
if( typeof blob.x != 'undefined' ) { fn(blob.x); }
Which was clearer when written without a check for undefined.
if( "x" in blob ) { fn(blob.x); }
But as has been mentioned these are not exactly the same (but are more than good enough for my needs).
if ( typeof( something ) == "undefined")
This worked for me while the others didn't.
I'm not sure where the origin of using === with typeof came from, and as a convention I see it used in many libraries, but the typeof operator returns a string literal, and we know that up front, so why would you also want to type check it too?
typeof x; // some string literal "string", "object", "undefined"
if (typeof x === "string") { // === is redundant because we already know typeof returns a string literal
if (typeof x == "string") { // sufficient
I didn't see (hope I didn't miss it) anyone checking the object before the property. So, this is the shortest and most effective (though not necessarily the most clear):
if (obj && obj.prop) {
// Do something;
}
If the obj or obj.prop is undefined, null, or "falsy", the if statement will not execute the code block. This is usually the desired behavior in most code block statements (in JavaScript).
UPDATE: (7/2/2021)
The latest version of JavaScript introduces a new operator for
optional chaining: ?.
This is probably going to be the most explicit and efficient method of checking for the existence of object properties, moving forward.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
Crossposting my answer from related question How can I check for "undefined" in JavaScript?.
Specific to this question, see test cases with someObject.<whatever>.
Some scenarios illustrating the results of the various answers:
http://jsfiddle.net/drzaus/UVjM4/
(Note that the use of var for in tests make a difference when in a scoped wrapper)
Code for reference:
(function(undefined) {
var definedButNotInitialized;
definedAndInitialized = 3;
someObject = {
firstProp: "1"
, secondProp: false
// , undefinedProp not defined
}
// var notDefined;
var tests = [
'definedButNotInitialized in window',
'definedAndInitialized in window',
'someObject.firstProp in window',
'someObject.secondProp in window',
'someObject.undefinedProp in window',
'notDefined in window',
'"definedButNotInitialized" in window',
'"definedAndInitialized" in window',
'"someObject.firstProp" in window',
'"someObject.secondProp" in window',
'"someObject.undefinedProp" in window',
'"notDefined" in window',
'typeof definedButNotInitialized == "undefined"',
'typeof definedButNotInitialized === typeof undefined',
'definedButNotInitialized === undefined',
'! definedButNotInitialized',
'!! definedButNotInitialized',
'typeof definedAndInitialized == "undefined"',
'typeof definedAndInitialized === typeof undefined',
'definedAndInitialized === undefined',
'! definedAndInitialized',
'!! definedAndInitialized',
'typeof someObject.firstProp == "undefined"',
'typeof someObject.firstProp === typeof undefined',
'someObject.firstProp === undefined',
'! someObject.firstProp',
'!! someObject.firstProp',
'typeof someObject.secondProp == "undefined"',
'typeof someObject.secondProp === typeof undefined',
'someObject.secondProp === undefined',
'! someObject.secondProp',
'!! someObject.secondProp',
'typeof someObject.undefinedProp == "undefined"',
'typeof someObject.undefinedProp === typeof undefined',
'someObject.undefinedProp === undefined',
'! someObject.undefinedProp',
'!! someObject.undefinedProp',
'typeof notDefined == "undefined"',
'typeof notDefined === typeof undefined',
'notDefined === undefined',
'! notDefined',
'!! notDefined'
];
var output = document.getElementById('results');
var result = '';
for(var t in tests) {
if( !tests.hasOwnProperty(t) ) continue; // bleh
try {
result = eval(tests[t]);
} catch(ex) {
result = 'Exception--' + ex;
}
console.log(tests[t], result);
output.innerHTML += "\n" + tests[t] + ": " + result;
}
})();
And results:
definedButNotInitialized in window: true
definedAndInitialized in window: false
someObject.firstProp in window: false
someObject.secondProp in window: false
someObject.undefinedProp in window: true
notDefined in window: Exception--ReferenceError: notDefined is not defined
"definedButNotInitialized" in window: false
"definedAndInitialized" in window: true
"someObject.firstProp" in window: false
"someObject.secondProp" in window: false
"someObject.undefinedProp" in window: false
"notDefined" in window: false
typeof definedButNotInitialized == "undefined": true
typeof definedButNotInitialized === typeof undefined: true
definedButNotInitialized === undefined: true
! definedButNotInitialized: true
!! definedButNotInitialized: false
typeof definedAndInitialized == "undefined": false
typeof definedAndInitialized === typeof undefined: false
definedAndInitialized === undefined: false
! definedAndInitialized: false
!! definedAndInitialized: true
typeof someObject.firstProp == "undefined": false
typeof someObject.firstProp === typeof undefined: false
someObject.firstProp === undefined: false
! someObject.firstProp: false
!! someObject.firstProp: true
typeof someObject.secondProp == "undefined": false
typeof someObject.secondProp === typeof undefined: false
someObject.secondProp === undefined: false
! someObject.secondProp: true
!! someObject.secondProp: false
typeof someObject.undefinedProp == "undefined": true
typeof someObject.undefinedProp === typeof undefined: true
someObject.undefinedProp === undefined: true
! someObject.undefinedProp: true
!! someObject.undefinedProp: false
typeof notDefined == "undefined": true
typeof notDefined === typeof undefined: true
notDefined === undefined: Exception--ReferenceError: notDefined is not defined
! notDefined: Exception--ReferenceError: notDefined is not defined
!! notDefined: Exception--ReferenceError: notDefined is not defined
If you do
if (myvar == undefined )
{
alert('var does not exists or is not initialized');
}
it will fail when the variable myvar does not exists, because myvar is not defined, so the script is broken and the test has no effect.
Because the window object has a global scope (default object) outside a function, a declaration will be 'attached' to the window object.
For example:
var myvar = 'test';
The global variable myvar is the same as window.myvar or window['myvar']
To avoid errors to test when a global variable exists, you better use:
if(window.myvar == undefined )
{
alert('var does not exists or is not initialized');
}
The question if a variable really exists doesn't matter, its value is incorrect. Otherwise, it is silly to initialize variables with undefined, and it is better use the value false to initialize. When you know that all variables that you declare are initialized with false, you can simply check its type or rely on !window.myvar to check if it has a proper/valid value. So even when the variable is not defined then !window.myvar is the same for myvar = undefined or myvar = false or myvar = 0.
When you expect a specific type, test the type of the variable. To speed up testing a condition you better do:
if( !window.myvar || typeof window.myvar != 'string' )
{
alert('var does not exists or is not type of string');
}
When the first and simple condition is true, the interpreter skips the next tests.
It is always better to use the instance/object of the variable to check if it got a valid value. It is more stable and is a better way of programming.
(y)
In the article Exploring the Abyss of Null and Undefined in JavaScript I read that frameworks like Underscore.js use this function:
function isUndefined(obj){
return obj === void 0;
}
Simply anything is not defined in JavaScript, is undefined, doesn't matter if it's a property inside an Object/Array or as just a simple variable...
JavaScript has typeof which make it very easy to detect an undefined variable.
Simply check if typeof whatever === 'undefined' and it will return a boolean.
That's how the famous function isUndefined() in AngularJs v.1x is written:
function isUndefined(value) {return typeof value === 'undefined';}
So as you see the function receive a value, if that value is defined, it will return false, otherwise for undefined values, return true.
So let's have a look what gonna be the results when we passing values, including object properties like below, this is the list of variables we have:
var stackoverflow = {};
stackoverflow.javascipt = 'javascript';
var today;
var self = this;
var num = 8;
var list = [1, 2, 3, 4, 5];
var y = null;
and we check them as below, you can see the results in front of them as a comment:
isUndefined(stackoverflow); //false
isUndefined(stackoverflow.javascipt); //false
isUndefined(today); //true
isUndefined(self); //false
isUndefined(num); //false
isUndefined(list); //false
isUndefined(y); //false
isUndefined(stackoverflow.java); //true
isUndefined(stackoverflow.php); //true
isUndefined(stackoverflow && stackoverflow.css); //true
As you see we can check anything with using something like this in our code, as mentioned you can simply use typeof in your code, but if you are using it over and over, create a function like the angular sample which I share and keep reusing as following DRY code pattern.
Also one more thing, for checking property on an object in a real application which you not sure even the object exists or not, check if the object exists first.
If you check a property on an object and the object doesn't exist, will throw an error and stop the whole application running.
isUndefined(x.css);
VM808:2 Uncaught ReferenceError: x is not defined(…)
So simple you can wrap inside an if statement like below:
if(typeof x !== 'undefined') {
//do something
}
Which also equal to isDefined in Angular 1.x...
function isDefined(value) {return typeof value !== 'undefined';}
Also other javascript frameworks like underscore has similar defining check, but I recommend you use typeof if you already not using any frameworks.
I also add this section from MDN which has got useful information about typeof, undefined and void(0).
Strict equality and undefined You can use undefined and the strict equality and inequality operators to determine whether a variable has
a value. In the following code, the variable x is not defined, and the
if statement evaluates to true.
var x;
if (x === undefined) {
// these statements execute
}
else {
// these statements do not execute
}
Note: The strict equality operator rather than the standard equality
operator must be used here, because x == undefined also checks whether
x is null, while strict equality doesn't. null is not equivalent to
undefined. See comparison operators for details.
Typeof operator and undefined
Alternatively, typeof can be used:
var x;
if (typeof x === 'undefined') {
// these statements execute
}
One reason to use typeof is that it does not throw an error if the
variable has not been declared.
// x has not been declared before
if (typeof x === 'undefined') { // evaluates to true without errors
// these statements execute
}
if (x === undefined) { // throws a ReferenceError
}
However, this kind of technique should be avoided. JavaScript is a
statically scoped language, so knowing if a variable is declared can
be read by seeing whether it is declared in an enclosing context. The
only exception is the global scope, but the global scope is bound to
the global object, so checking the existence of a variable in the
global context can be done by checking the existence of a property on
the global object (using the in operator, for instance).
Void operator and undefined
The void operator is a third alternative.
var x;
if (x === void 0) {
// these statements execute
}
// y has not been declared before
if (y === void 0) {
// throws a ReferenceError (in contrast to `typeof`)
}
more > here
ECMAScript 10 introduced a new feature - optional chaining which you can use to use a property of an object only when an object is defined like this:
const userPhone = user?.contactDetails?.phone;
It will reference to the phone property only when user and contactDetails are defined.
Ref. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
'if (window.x) { }' is error safe
Most likely you want if (window.x). This check is safe even if x hasn't been declared (var x;) - browser doesn't throw an error.
Example: I want to know if my browser supports History API
if (window.history) {
history.call_some_function();
}
How this works:
window is an object which holds all global variables as its members, and it is legal to try to access a non-existing member. If x hasn't been declared or hasn't been set then window.x returns undefined. undefined leads to false when if() evaluates it.
Reading through this, I'm amazed I didn't see this. I have found multiple algorithms that would work for this.
Never Defined
If the value of an object was never defined, this will prevent from returning true if it is defined as null or undefined. This is helpful if you want true to be returned for values set as undefined
if(obj.prop === void 0) console.log("The value has never been defined");
Defined as undefined Or never Defined
If you want it to result as true for values defined with the value of undefined, or never defined, you can simply use === undefined
if(obj.prop === undefined) console.log("The value is defined as undefined, or never defined");
Defined as a falsy value, undefined,null, or never defined.
Commonly, people have asked me for an algorithm to figure out if a value is either falsy, undefined, or null. The following works.
if(obj.prop == false || obj.prop === null || obj.prop === undefined) {
console.log("The value is falsy, null, or undefined");
}
"propertyName" in obj //-> true | false
The solution is incorrect. In JavaScript,
null == undefined
will return true, because they both are "casted" to a boolean and are false. The correct way would be to check
if (something === undefined)
which is the identity operator...
Compare with void 0, for terseness.
if (foo !== void 0)
It's not as verbose as if (typeof foo !== 'undefined')
You can get an array all undefined with path using the following code.
function getAllUndefined(object) {
function convertPath(arr, key) {
var path = "";
for (var i = 1; i < arr.length; i++) {
path += arr[i] + "->";
}
path += key;
return path;
}
var stack = [];
var saveUndefined= [];
function getUndefiend(obj, key) {
var t = typeof obj;
switch (t) {
case "object":
if (t === null) {
return false;
}
break;
case "string":
case "number":
case "boolean":
case "null":
return false;
default:
return true;
}
stack.push(key);
for (k in obj) {
if (obj.hasOwnProperty(k)) {
v = getUndefiend(obj[k], k);
if (v) {
saveUndefined.push(convertPath(stack, k));
}
}
}
stack.pop();
}
getUndefiend({
"": object
}, "");
return saveUndefined;
}
jsFiddle link
There is a nice and elegant way to assign a defined property to a new variable if it is defined or assign a default value to it as a fallback if it’s undefined.
var a = obj.prop || defaultValue;
It’s suitable if you have a function, which receives an additional configuration property:
var yourFunction = function(config){
this.config = config || {};
this.yourConfigValue = config.yourConfigValue || 1;
console.log(this.yourConfigValue);
}
Now executing
yourFunction({yourConfigValue:2});
//=> 2
yourFunction();
//=> 1
yourFunction({otherProperty:5});
//=> 1
Here is my situation:
I am using the result of a REST call. The result should be parsed from JSON to a JavaScript object.
There is one error I need to defend. If the arguments to the REST call were incorrect as far as the user specifying the arguments wrong, the REST call comes back basically empty.
While using this post to help me defend against this, I tried this:
if( typeof restResult.data[0] === "undefined" ) { throw "Some error"; }
For my situation, if restResult.data[0] === "object", then I can safely start inspecting the rest of the members. If undefined then throw the error as above.
What I am saying is that for my situation, all the previous suggestions in this post did not work. I'm not saying I'm right and everyone is wrong. I am not a JavaScript master at all, but hopefully this will help someone.
All the answers are incomplete. This is the right way of knowing that there is a property 'defined as undefined':
var hasUndefinedProperty = function hasUndefinedProperty(obj, prop){
return ((prop in obj) && (typeof obj[prop] == 'undefined'));
};
Example:
var a = { b : 1, e : null };
a.c = a.d;
hasUndefinedProperty(a, 'b'); // false: b is defined as 1
hasUndefinedProperty(a, 'c'); // true: c is defined as undefined
hasUndefinedProperty(a, 'd'); // false: d is undefined
hasUndefinedProperty(a, 'e'); // false: e is defined as null
// And now...
delete a.c ;
hasUndefinedProperty(a, 'c'); // false: c is undefined
Too bad that this been the right answer and is buried in wrong answers >_<
So, for anyone who pass by, I will give you undefined's for free!!
var undefined ; undefined ; // undefined
({}).a ; // undefined
[].a ; // undefined
''.a ; // undefined
(function(){}()) ; // undefined
void(0) ; // undefined
eval() ; // undefined
1..a ; // undefined
/a/.a ; // undefined
(true).a ; // undefined
Going through the comments, for those who want to check both is it undefined or its value is null:
//Just in JavaScript
var s; // Undefined
if (typeof s == "undefined" || s === null){
alert('either it is undefined or value is null')
}
If you are using jQuery Library then jQuery.isEmptyObject() will suffice for both cases,
var s; // Undefined
jQuery.isEmptyObject(s); // Will return true;
s = null; // Defined as null
jQuery.isEmptyObject(s); // Will return true;
//Usage
if (jQuery.isEmptyObject(s)) {
alert('Either variable:s is undefined or its value is null');
} else {
alert('variable:s has value ' + s);
}
s = 'something'; // Defined with some value
jQuery.isEmptyObject(s); // Will return false;
If you are using Angular:
angular.isUndefined(obj)
angular.isUndefined(obj.prop)
Underscore.js:
_.isUndefined(obj)
_.isUndefined(obj.prop)
I provide three ways here for those who expect weird answers:
function isUndefined1(val) {
try {
val.a;
} catch (e) {
return /undefined/.test(e.message);
}
return false;
}
function isUndefined2(val) {
return !val && val+'' === 'undefined';
}
function isUndefined3(val) {
const defaultVal = {};
return ((input = defaultVal) => input === defaultVal)(val);
}
function test(func){
console.group(`test start :`+func.name);
console.log(func(undefined));
console.log(func(null));
console.log(func(1));
console.log(func("1"));
console.log(func(0));
console.log(func({}));
console.log(func(function () { }));
console.groupEnd();
}
test(isUndefined1);
test(isUndefined2);
test(isUndefined3);
isUndefined1:
Try to get a property of the input value, and check the error message if it exists. If the input value is undefined, the error message would be Uncaught TypeError: Cannot read property 'b' of undefined.
isUndefined2:
Convert the input value to a string to compare with "undefined" and ensure it's a negative value.
isUndefined3:
In JavaScript, an optional parameter works when the input value is exactly undefined.
There is a very easy and simple way.
You can use optional chaining:
x = {prop:{name:"sajad"}}
console.log(x.prop?.name) // Output is: "sajad"
console.log(x.prop?.lastName) // Output is: undefined
or
if(x.prop?.lastName) // The result of this 'if' statement is false and is not throwing an error
You can use optional chaining even for functions or arrays.
As of mid-2020 this is not universally implemented. Check the documentation at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
I use if (this.variable) to test if it is defined. A simple if (variable), recommended in a previous answer, fails for me.
It turns out that it works only when a variable is a field of some object, obj.someField to check if it is defined in the dictionary. But we can use this or window as the dictionary object since any variable is a field in the current window, as I understand it. Therefore here is a test:
if (this.abc)
alert("defined");
else
alert("undefined");
abc = "abc";
if (this.abc)
alert("defined");
else
alert("undefined");
It first detects that variable abc is undefined and it is defined after initialization.
function isUnset(inp) {
return (typeof inp === 'undefined')
}
Returns false if variable is set, and true if is undefined.
Then use:
if (isUnset(var)) {
// initialize variable here
}
I would like to show you something I'm using in order to protect the undefined variable:
Object.defineProperty(window, 'undefined', {});
This forbids anyone to change the window.undefined value therefore destroying the code based on that variable. If using "use strict", anything trying to change its value will end in error, otherwise it would be silently ignored.

Categories