Javascript - Detecting defined variable as undefined - javascript

For example:
var myObj = {
yes: undefined
}
console.log(typeof myObj.yes === 'undefined') //--> true
console.log(typeof myObj.nop === 'undefined') //--> true too
Is there a way to detect if myObj.nop is not defined as undefined ?

You would use in:
if('yes' in myObj) {
// then we know the key exists, even if its value is undefined
}
Keep in mind, this also checks for properties in the object's prototype, which is probably fine in your case, but in case you only want to check properties that are directly set on that specific object, you can use Object.prototype.hasOwnProperty:
if(myObj.hasOwnProperty('yes')) {
// then it exists on that object
}
Here's a good article on the difference between the two.

Use hasOwnProperty.
myObj.hasOwnProperty('yes'); // returns true
myObj.hasOwnProperty('nop'); // returns false

var myObj = {
yes: undefined
}
console.log( myObj.yes === undefined); // gives true
and
var myObj = {
yes: 'any value here'
}
console.log( myObj.yes === undefined); // gives false
One thing to note here is that the undefined is not in single quotes. May be this gives you right direction.

Related

How to return an Object Value if you have a specific key in your Object? [duplicate]

How do I check if an object has a specific property in JavaScript?
Consider:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
Is that the best way to do it?
2022 UPDATE
Object.hasOwn()
Object.hasOwn() is recommended over Object.hasOwnProperty() because it works for objects created using Object.create(null) and with objects that have overridden the inherited hasOwnProperty() method. While it is possible to workaround these problems by calling Object.prototype.hasOwnProperty() on an external object, Object.hasOwn() is more intuitive.
Example
const object1 = {
prop: 'exists'
};
console.log(Object.hasOwn(object1, 'prop'));
// expected output: true
Original answer
I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to typeof this[property] or, even worse, x.key will give you completely misleading results.
It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then object.hasOwnProperty is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.)
If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: prop in object will give you your desired effect.
Since using hasOwnProperty is probably what you want, and considering that you may want a fallback method, I present to you the following solution:
var obj = {
a: undefined,
b: null,
c: false
};
// a, b, c all found
for ( var prop in obj ) {
document.writeln( "Object1: " + prop );
}
function Class(){
this.a = undefined;
this.b = null;
this.c = false;
}
Class.prototype = {
a: undefined,
b: true,
c: true,
d: true,
e: true
};
var obj2 = new Class();
// a, b, c, d, e found
for ( var prop in obj2 ) {
document.writeln( "Object2: " + prop );
}
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
if ( Object.prototype.hasOwnProperty ) {
var hasOwnProperty = function(obj, prop) {
return obj.hasOwnProperty(prop);
}
}
// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
if ( hasOwnProperty(obj2, prop) ) {
document.writeln( "Object2 w/ hasOwn: " + prop );
}
}
The above is a working, cross-browser, solution to hasOwnProperty(), with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.
With Underscore.js or (even better) Lodash:
_.has(x, 'key');
Which calls Object.prototype.hasOwnProperty, but (a) is shorter to type, and (b) uses "a safe reference to hasOwnProperty" (i.e. it works even if hasOwnProperty is overwritten).
In particular, Lodash defines _.has as:
function has(object, key) {
return object ? hasOwnProperty.call(object, key) : false;
}
// hasOwnProperty = Object.prototype.hasOwnProperty
You can use this (but read the warning below):
var x = {
'key': 1
};
if ('key' in x) {
console.log('has');
}
But be warned: 'constructor' in x will return true even if x is an empty object - same for 'toString' in x, and many others. It's better to use Object.hasOwn(x, 'key').
Note: the following is nowadays largely obsolete thanks to strict mode, and hasOwnProperty. The correct solution is to use strict mode and to check for the presence of a property using obj.hasOwnProperty. This answer predates both these things, at least as widely implemented (yes, it is that old). Take the following as a historical note.
Bear in mind that undefined is (unfortunately) not a reserved word in JavaScript if you’re not using strict mode. Therefore, someone (someone else, obviously) could have the grand idea of redefining it, breaking your code.
A more robust method is therefore the following:
if (typeof(x.attribute) !== 'undefined')
On the flip side, this method is much more verbose and also slower. :-/
A common alternative is to ensure that undefined is actually undefined, e.g. by putting the code into a function which accepts an additional parameter, called undefined, that isn’t passed a value. To ensure that it’s not passed a value, you could just call it yourself immediately, e.g.:
(function (undefined) {
… your code …
if (x.attribute !== undefined)
… mode code …
})();
if (x.key !== undefined)
Armin Ronacher seems to have already beat me to it, but:
Object.prototype.hasOwnProperty = function(property) {
return this[property] !== undefined;
};
x = {'key': 1};
if (x.hasOwnProperty('key')) {
alert('have key!');
}
if (!x.hasOwnProperty('bar')) {
alert('no bar!');
}
A safer, but slower solution, as pointed out by Konrad Rudolph and Armin Ronacher would be:
Object.prototype.hasOwnProperty = function(property) {
return typeof this[property] !== 'undefined';
};
Considering the following object in Javascript
const x = {key: 1};
You can use the in operator to check if the property exists on an object:
console.log("key" in x);
You can also loop through all the properties of the object using a for - in loop, and then check for the specific property:
for (const prop in x) {
if (prop === "key") {
//Do something
}
}
You must consider if this object property is enumerable or not, because non-enumerable properties will not show up in a for-in loop. Also, if the enumerable property is shadowing a non-enumerable property of the prototype, it will not show up in Internet Explorer 8 and earlier.
If you’d like a list of all instance properties, whether enumerable or not, you can use
Object.getOwnPropertyNames(x);
This will return an array of names of all properties that exist on an object.
Reflections provide methods that can be used to interact with Javascript objects. The static Reflect.has() method works like the in operator as a function.
console.log(Reflect.has(x, 'key'));
// expected output: true
console.log(Reflect.has(x, 'key2'));
// expected output: false
console.log(Reflect.has(object1, 'toString'));
// expected output: true
Finally, you can use the typeof operator to directly check the data type of the object property:
if (typeof x.key === "undefined") {
console.log("undefined");
}
If the property does not exist on the object, it will return the string undefined. Else it will return the appropriate property type. However, note that this is not always a valid way of checking if an object has a property or not, because you could have a property that is set to undefined, in which case, using typeof x.key would still return true (even though the key is still in the object).
Similarly, you can check if a property exists by comparing directly to the undefined Javascript property
if (x.key === undefined) {
console.log("undefined");
}
This should work unless key was specifically set to undefined on the x object
Let's cut through some confusion here. First, let's simplify by assuming hasOwnProperty already exists; this is true of the vast majority of current browsers in use.
hasOwnProperty returns true if the attribute name that is passed to it has been added to the object. It is entirely independent of the actual value assigned to it which may be exactly undefined.
Hence:
var o = {}
o.x = undefined
var a = o.hasOwnProperty('x') // a is true
var b = o.x === undefined // b is also true
However:
var o = {}
var a = o.hasOwnProperty('x') // a is now false
var b = o.x === undefined // b is still true
The problem is what happens when an object in the prototype chain has an attribute with the value of undefined? hasOwnProperty will be false for it, and so will !== undefined. Yet, for..in will still list it in the enumeration.
The bottom line is there is no cross-browser way (since Internet Explorer doesn't expose __prototype__) to determine that a specific identifier has not been attached to an object or anything in its prototype chain.
If you are searching for a property, then "no". You want:
if ('prop' in obj) { }
In general, you should not care whether or not the property comes from the prototype or the object.
However, because you used 'key' in your sample code, it looks like you are treating the object as a hash, in which case your answer would make sense. All of the hashes keys would be properties in the object, and you avoid the extra properties contributed by the prototype.
John Resig's answer was very comprehensive, but I thought it wasn't clear. Especially with when to use "'prop' in obj".
For testing simple objects, use:
if (obj[x] !== undefined)
If you don't know what object type it is, use:
if (obj.hasOwnProperty(x))
All other options are slower...
Details
A performance evaluation of 100,000,000 cycles under Node.js to the five options suggested by others here:
function hasKey1(k,o) { return (x in obj); }
function hasKey2(k,o) { return (obj[x]); }
function hasKey3(k,o) { return (obj[x] !== undefined); }
function hasKey4(k,o) { return (typeof(obj[x]) !== 'undefined'); }
function hasKey5(k,o) { return (obj.hasOwnProperty(x)); }
The evaluation tells us that unless we specifically want to check the object's prototype chain as well as the object itself, we should not use the common form:
if (X in Obj)...
It is between 2 to 6 times slower depending on the use case
hasKey1 execution time: 4.51 s
hasKey2 execution time: 0.90 s
hasKey3 execution time: 0.76 s
hasKey4 execution time: 0.93 s
hasKey5 execution time: 2.15 s
Bottom line, if your Obj is not necessarily a simple object and you wish to avoid checking the object's prototype chain and to ensure x is owned by Obj directly, use if (obj.hasOwnProperty(x))....
Otherwise, when using a simple object and not being worried about the object's prototype chain, using if (typeof(obj[x]) !== 'undefined')... is the safest and fastest way.
If you use a simple object as a hash table and never do anything kinky, I would use if (obj[x])... as I find it much more readable.
Yes it is :) I think you can also do Object.prototype.hasOwnProperty.call(x, 'key') which should also work if x has a property called hasOwnProperty :)
But that tests for own properties. If you want to check if it has an property that may also be inhered you can use typeof x.foo != 'undefined'.
if(x.hasOwnProperty("key")){
// …
}
because
if(x.key){
// …
}
fails if x.key is falsy (for example, x.key === "").
You can also use the ES6 Reflect object:
x = {'key': 1};
Reflect.has( x, 'key'); // returns true
Documentation on MDN for Reflect.has can be found here.
The static Reflect.has() method works like the in operator as a function.
Do not do this object.hasOwnProperty(key)). It's really bad because these methods may be shadowed by properties on the object in question - consider { hasOwnProperty: false } - or, the object may be a null object (Object.create(null)).
The best way is to do Object.prototype.hasOwnProperty.call(object, key) or:
const has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.
console.log(has.call(object, key));
/* Or */
import has from 'has'; // https://www.npmjs.com/package/has
console.log(has(object, key));
OK, it looks like I had the right answer unless if you don't want inherited properties:
if (x.hasOwnProperty('key'))
Here are some other options to include inherited properties:
if (x.key) // Quick and dirty, but it does the same thing as below.
if (x.key !== undefined)
Another relatively simple way is using Object.keys. This returns an array which means you get all of the features of an array.
var noInfo = {};
var info = {something: 'data'};
Object.keys(noInfo).length //returns 0 or false
Object.keys(info).length //returns 1 or true
Although we are in a world with great browser support. Because this question is so old I thought I'd add this:
This is safe to use as of JavaScript v1.8.5.
JavaScript is now evolving and growing as it now has good and even efficient ways to check it.
Here are some easy ways to check if object has a particular property:
Using hasOwnProperty()
const hero = {
name: 'Batman'
};
hero.hasOwnProperty('name'); // => true
hero.hasOwnProperty('realName'); // => false
Using keyword/operator in
const hero = {
name: 'Batman'
};
'name' in hero; // => true
'realName' in hero; // => false
Comparing with undefined keyword
const hero = {
name: 'Batman'
};
hero.name; // => 'Batman'
hero.realName; // => undefined
// So consider this
hero.realName == undefined // => true (which means property does not exists in object)
hero.name == undefined // => false (which means that property exists in object)
For more information, check here.
hasOwnProperty "can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain."
So most probably, for what seems by your question, you don't want to use hasOwnProperty, which determines if the property exists as attached directly to the object itself,.
If you want to determine if the property exists in the prototype chain, you may want to use it like:
if (prop in object) { // Do something }
You can use the following approaches-
var obj = {a:1}
console.log('a' in obj) // 1
console.log(obj.hasOwnProperty('a')) // 2
console.log(Boolean(obj.a)) // 3
The difference between the following approaches are as follows-
In the first and third approach we are not just searching in object but its prototypal chain too. If the object does not have the property, but the property is present in its prototype chain it is going to give true.
var obj = {
a: 2,
__proto__ : {b: 2}
}
console.log('b' in obj)
console.log(Boolean(obj.b))
The second approach will check only for its own properties. Example -
var obj = {
a: 2,
__proto__ : {b: 2}
}
console.log(obj.hasOwnProperty('b'))
The difference between the first and the third is if there is a property which has value undefined the third approach is going to give false while first will give true.
var obj = {
b : undefined
}
console.log(Boolean(obj.b))
console.log('b' in obj);
Given myObject object and “myKey” as key name:
Object.keys(myObject).includes('myKey')
or
myObject.hasOwnProperty('myKey')
or
typeof myObject.myKey !== 'undefined'
The last was widely used, but (as pointed out in other answers and comments) it could also match on keys deriving from Object prototype.
Performance
Today 2020.12.17 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v83 for chosen solutions.
Results
I compare only solutions A-F because they give valid result for all cased used in snippet in details section. For all browsers
solution based on in (A) is fast or fastest
solution (E) is fastest for chrome for big objects and fastest for firefox for small arrays if key not exists
solution (F) is fastest (~ >10x than other solutions) for small arrays
solutions (D,E) are quite fast
solution based on losash has (B) is slowest
Details
I perform 4 tests cases:
when object has 10 fields and searched key exists - you can run it HERE
when object has 10 fields and searched key not exists - you can run it HERE
when object has 10000 fields and searched key exists - you can run it HERE
when object has 10000 fields and searched key exists - you can run it HERE
Below snippet presents differences between solutions
A
B
C
D
E
F
G
H
I
J
K
// SO https://stackoverflow.com/q/135448/860099
// src: https://stackoverflow.com/a/14664748/860099
function A(x) {
return 'key' in x
}
// src: https://stackoverflow.com/a/11315692/860099
function B(x) {
return _.has(x, 'key')
}
// src: https://stackoverflow.com/a/40266120/860099
function C(x) {
return Reflect.has( x, 'key')
}
// src: https://stackoverflow.com/q/135448/860099
function D(x) {
return x.hasOwnProperty('key')
}
// src: https://stackoverflow.com/a/11315692/860099
function E(x) {
return Object.prototype.hasOwnProperty.call(x, 'key')
}
// src: https://stackoverflow.com/a/136411/860099
function F(x) {
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
return hasOwnProperty(x,'key')
}
// src: https://stackoverflow.com/a/135568/860099
function G(x) {
return typeof(x.key) !== 'undefined'
}
// src: https://stackoverflow.com/a/22740939/860099
function H(x) {
return x.key !== undefined
}
// src: https://stackoverflow.com/a/38332171/860099
function I(x) {
return !!x.key
}
// src: https://stackoverflow.com/a/41184688/860099
function J(x) {
return !!x['key']
}
// src: https://stackoverflow.com/a/54196605/860099
function K(x) {
return Boolean(x.key)
}
// --------------------
// TEST
// --------------------
let x1 = {'key': 1};
let x2 = {'key': "1"};
let x3 = {'key': true};
let x4 = {'key': []};
let x5 = {'key': {}};
let x6 = {'key': ()=>{}};
let x7 = {'key': ''};
let x8 = {'key': 0};
let x9 = {'key': false};
let x10= {'key': undefined};
let x11= {'nokey': 1};
let b= x=> x ? 1:0;
console.log(' 1 2 3 4 5 6 7 8 9 10 11');
[A,B,C,D,E,F,G,H,I,J,K ].map(f=> {
console.log(
`${f.name} ${b(f(x1))} ${b(f(x2))} ${b(f(x3))} ${b(f(x4))} ${b(f(x5))} ${b(f(x6))} ${b(f(x7))} ${b(f(x8))} ${b(f(x9))} ${b(f(x10))} ${b(f(x11))} `
)})
console.log('\nLegend: Columns (cases)');
console.log('1. key = 1 ');
console.log('2. key = "1" ');
console.log('3. key = true ');
console.log('4. key = [] ');
console.log('5. key = {} ');
console.log('6. key = ()=>{} ');
console.log('7. key = "" ');
console.log('8. key = 0 ');
console.log('9. key = false ');
console.log('10. key = undefined ');
console.log('11. no-key ');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
This shippet only presents functions used in performance tests - it not perform tests itself!
And here are example results for chrome
Now with ECMAScript22 we can use hasOwn instead of hasOwnProperty (Because this feature has pitfalls )
Object.hasOwn(obj, propKey)
Here is another option for a specific case. :)
If you want to test for a member on an object and want to know if it has been set to something other than:
''
false
null
undefined
0
...
then you can use:
var foo = {};
foo.bar = "Yes, this is a proper value!";
if (!!foo.bar) {
// member is set, do something
}
some easier and short options depending on the specific use case:
to check if the property exists, regardless of value, use the in operator ("a" in b)
to check a property value from a variable, use bracket notation (obj[v])
to check a property value as truthy, use optional
chaining (?.)
to check a property value boolean, use double-not / bang-bang / (!!)
to set a default value for null / undefined check, use nullish coalescing operator (??)
to set a default value for falsey value check, use short-circuit logical OR operator (||)
run the code snippet to see results:
let obj1 = {prop:undefined};
console.log(1,"prop" in obj1);
console.log(1,obj1?.prop);
let obj2 = undefined;
//console.log(2,"prop" in obj2); would throw because obj2 undefined
console.log(2,"prop" in (obj2 ?? {}))
console.log(2,obj2?.prop);
let obj3 = {prop:false};
console.log(3,"prop" in obj3);
console.log(3,!!obj3?.prop);
let obj4 = {prop:null};
let look = "prop"
console.log(4,"prop" in obj4);
console.log(4,obj4?.[look]);
let obj5 = {prop:true};
console.log(5,"prop" in obj5);
console.log(5,obj5?.prop === true);
let obj6 = {otherProp:true};
look = "otherProp"
console.log(6,"prop" in obj6);
console.log(6,obj6.look); //should have used bracket notation
let obj7 = {prop:""};
console.log(7,"prop" in obj7);
console.log(7,obj7?.prop || "empty");
I see very few instances where hasOwn is used properly, especially given its inheritance issues
There is a method, "hasOwnProperty", that exists on an object, but it's not recommended to call this method directly, because it might be sometimes that the object is null or some property exist on the object like: { hasOwnProperty: false }
So a better way would be:
// Good
var obj = {"bar": "here bar desc"}
console.log(Object.prototype.hasOwnProperty.call(obj, "bar"));
// Best
const has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.
console.log(has.call(obj, "bar"));
An ECMAScript 6 solution with reflection. Create a wrapper like:
/**
Gets an argument from array or object.
The possible outcome:
- If the key exists the value is returned.
- If no key exists the default value is returned.
- If no default value is specified an empty string is returned.
#param obj The object or array to be searched.
#param key The name of the property or key.
#param defVal Optional default version of the command-line parameter [default ""]
#return The default value in case of an error else the found parameter.
*/
function getSafeReflectArg( obj, key, defVal) {
"use strict";
var retVal = (typeof defVal === 'undefined' ? "" : defVal);
if ( Reflect.has( obj, key) ) {
return Reflect.get( obj, key);
}
return retVal;
} // getSafeReflectArg
Showing how to use this answer
const object= {key1: 'data', key2: 'data2'};
Object.keys(object).includes('key1') //returns true
We can use indexOf as well, I prefer includes
You need to use the method object.hasOwnProperty(property). It returns true if the object has the property and false if the object doesn't.
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
const object1 = {};
object1.property1 = 42;
console.log(object1.hasOwnProperty('property1'));
// expected output: true
console.log(object1.hasOwnProperty('toString'));
// expected output: false
console.log(object1.hasOwnProperty('hasOwnProperty'));
// expected output: false
Know more
Don't over-complicate things when you can do:
var isProperty = (objectname.keyname || "") ? true : false;
It Is simple and clear for most cases...
A Better approach for iterating on object's own properties:
If you want to iterate on object's properties without using hasOwnProperty() check,
use for(let key of Object.keys(stud)){} method:
for(let key of Object.keys(stud)){
console.log(key); // will only log object's Own properties
}
full Example and comparison with for-in with hasOwnProperty()
function Student() {
this.name = "nitin";
}
Student.prototype = {
grade: 'A'
}
let stud = new Student();
// for-in approach
for(let key in stud){
if(stud.hasOwnProperty(key)){
console.log(key); // only outputs "name"
}
}
//Object.keys() approach
for(let key of Object.keys(stud)){
console.log(key);
}

MSCRM 2011 Javascript condition issue

I have a problem with putting condition on javascript.
In case form I'm using below code. When i enter material code manually everything is ok but when i use search help it gives me an error. When i check it on debugger i see 2 situations based on my method of entering code.
Can you help me to improve my code below, its not working properly.
Gives me error on step if (lookuptextvalue.name_Value.value)if i enter material code using search help.
function matName() {
var lookupObject = Xrm.Page.getAttribute("new_material");
if (lookupObject != null)
{
var lookUpObjectValue = lookupObject.getValue();
if ((lookUpObjectValue != null))
{
var lookuptextvalue = lookUpObjectValue[0].keyValues;
if (lookuptextvalue.name_Value.value) {
var lookuptextvaluex = lookUpObjectValue[0].keyValues.name_Value.value;
}
else if(lookuptextvalue.name.value) {
var lookuptextvaluex = lookUpObjectValue[0].keyValues.name.value;
}
var lookupid = lookUpObjectValue[0].id;
Xrm.Page.getAttribute("new_matname").setValue(lookuptextvaluex);
}
else {
Xrm.Page.getAttribute("new_matname").setValue();
}
}
}
Thanks Elda.
This is such a common error that gets people new to javascript.
if(this.myData.myValue){ ...
// throws: Uncaught TypeError: Cannot read property 'myValue' of undefined`
Many will look at myValue for the problem but if you read the error carefully it is saying it can not find the property myValue of undefined. It is not myValue that is the issue but myData that is not defined and hence can not have any properties. I personly would like the error to read Uncaught TypeError: 'myData' is undefined and has no property 'myValue' as this would stop so many getting stuck on where the problem is.
undefined is a special object in javascript and crops up everywhere. undefined is equivalent to false. undefined is assigned to a object that is not initiated. Objects that have not been defined are equal to undefined. Object that have the value undefined are not placed in JSON files. undefined is not allowed in JSON files unless it is a string. Object that have the value undefined can not have properties. undefined is a primitive type.
Examples
var myObj; // declare a variable without a value. It automatically gets undefined
// you can check if the object has a value
if(myObj === undefined){ // will be true if myObj has no value
// this does not mean it has been declare
if(myOtherObj === undefined){ // will return true as well even thought myOtherObj has not been declared
To check if a variable has been declared use void 0
// from above code snippet
if(myObj === void 0){ // is true because myObj has been declared
if(myOtherObj === void 0){ // is false because myOtherObj has not been declared.
Many people use the sort cut to determine if an object is undefined. This can cause problems if you are not careful.
if(!myObj){ // will be true if my object is undefined.
// this is bad practice because the Numbers 0, the boolean false,
// the Object null are also equivalent to false;
myObj = 0
if(!myObj){ // the test intended to find out if myObj has been defined fails
myObj = false
if(!myObj){ // again the test fails.
myObj = null
if(!myObj){ // again.
I always insist that people use the exact equivalence operator === to test for undefined
if(myObj === undefined){
Unlike C/C++ and other similar languages the order of a conditional statement is always left to right. JavaScript will exit the conditional statment as soon as it knows that it has failed. This is handy for testing for undefined
The following is also the solution to the question.
var myObj;
if(myObj !== undefined && myObj.myProperty){ // this will not crash
// because if myObj is undefined
// it will exit at the first
// condition.
// on the other hand this will
if(myObj.myProperty && myObj !== undefined){ // this will throw an error if
// myObj is undefined
undefined is equivalent to some other javascipt types
undefined == null // true
undefined == false // false
undefined == 0 // false
undefined === null // false
undefined === false // false
undefined === 0 // false
// be careful as the ! operator changes things a little
var a = undefined;
!a //true
a = 0;
!a // true
a = null;
!a // true
a = false;
!a // true
JSON files can not have undefined as a value.
{
"myObj" : undefined
}
// this is not a valid JSON file.
When stringifing an object to JSON all objects that have the value undefined will not be added to the JSON string
var myObj = {
propA : 0,
propB : "hello",
propC : undefined,
propD : null
};
var str = JSON.stringify(myObj); // will create the JSON string
{
"propA" : 0,
"propB" : "hello",
"propD" : null
}
// not that propC does not appear in the JSON
undefined is a complicated beast in JavaScript and it is best to become familiar with its uses.
Learn more at
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined

How to check if object property exists with a variable holding the property name?

I am checking for the existence of an object property with a variable holding the property name in question.
var myObj;
myObj.prop = "exists";
var myProp = "p"+"r"+"o"+"p";
if(myObj.myProp){
alert("yes, i have that property");
};
This is undefined because it's looking for myObj.myProp but I want it to check for myObj.prop
var myProp = 'prop';
if(myObj.hasOwnProperty(myProp)){
alert("yes, i have that property");
}
Or
var myProp = 'prop';
if(myProp in myObj){
alert("yes, i have that property");
}
Or
if('prop' in myObj){
alert("yes, i have that property");
}
Note that hasOwnProperty doesn't check for inherited properties, whereas in does. For example 'constructor' in myObj is true, but myObj.hasOwnProperty('constructor') is not.
You can use hasOwnProperty, but based on the reference you need quotes when using this method:
if (myObj.hasOwnProperty('myProp')) {
// do something
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
Another way is to use in operator, but you need quotes here as well:
if ('myProp' in myObj) {
// do something
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
Thank you for everyone's assistance and pushing to get rid of the eval statement.
Variables needed to be in brackets, not dot notation. This works and is clean, proper code.
Each of these are variables: appChoice, underI, underObstr.
if(typeof tData.tonicdata[appChoice][underI][underObstr] !== "undefined"){
//enter code here
}
For own property :
var loan = { amount: 150 };
if(Object.prototype.hasOwnProperty.call(loan, "amount"))
{
//will execute
}
Note: using Object.prototype.hasOwnProperty is better than loan.hasOwnProperty(..), in case a custom hasOwnProperty is defined in the prototype chain (which is not the case here), like
var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
To include inherited properties in the finding use the in operator: (but you must place an object at the right side of 'in', primitive values will throw error, e.g. 'length' in 'home' will throw error, but 'length' in new String('home') won't)
const yoshi = { skulk: true };
const hattori = { sneak: true };
const kuma = { creep: true };
if ("skulk" in yoshi)
console.log("Yoshi can skulk");
if (!("sneak" in yoshi))
console.log("Yoshi cannot sneak");
if (!("creep" in yoshi))
console.log("Yoshi cannot creep");
Object.setPrototypeOf(yoshi, hattori);
if ("sneak" in yoshi)
console.log("Yoshi can now sneak");
if (!("creep" in hattori))
console.log("Hattori cannot creep");
Object.setPrototypeOf(hattori, kuma);
if ("creep" in hattori)
console.log("Hattori can now creep");
if ("creep" in yoshi)
console.log("Yoshi can also creep");
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
Note: One may be tempted to use typeof and [ ] property accessor as the following code which doesn't work always ...
var loan = { amount: 150 };
loan.installment = undefined;
if("installment" in loan) // correct
{
// will execute
}
if(typeof loan["installment"] !== "undefined") // incorrect
{
// will not execute
}
A much more secure way to check if property exists on the object is to use empty object or object prototype to call hasOwnProperty()
var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
foo.hasOwnProperty('bar'); // always returns false
// Use another Object's hasOwnProperty and call it with 'this' set to foo
({}).hasOwnProperty.call(foo, 'bar'); // true
// It's also possible to use the hasOwnProperty property from the Object
// prototype for this purpose
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
Reference from MDN Web Docs - Object.prototype.hasOwnProperty()
there are much simpler solutions and I don't see any answer to your actual question:
"it's looking for myObj.myProp but I want it to check for myObj.prop"
to obtain a property value from a variable, use bracket notation.
to test that property for truthy values, use optional
chaining
to return a boolean, use double-not / bang-bang / (!!)
use the in operator if you are certain you have an object and only want to check for the existence of the property (true even if prop value is undefined). or perhaps combine with nullish coalescing operator ?? to avoid errors being thrown.
var nothing = undefined;
var obj = {prop:"hello world"}
var myProp = "prop";
consolelog( 1,()=> obj.myProp); // obj does not have a "myProp"
consolelog( 2,()=> obj[myProp]); // brackets works
consolelog( 3,()=> nothing[myProp]); // throws if not an object
consolelog( 4,()=> obj?.[myProp]); // optional chaining very nice ⭐️⭐️⭐️⭐️⭐️
consolelog( 5,()=> nothing?.[myProp]); // optional chaining avoids throwing
consolelog( 6,()=> nothing?.[nothing]); // even here it is error-safe
consolelog( 7,()=> !!obj?.[myProp]); // double-not yields true
consolelog( 8,()=> !!nothing?.[myProp]); // false because undefined
consolelog( 9,()=> myProp in obj); // in operator works
consolelog(10,()=> myProp in nothing); // throws if not an object
consolelog(11,()=> myProp in (nothing ?? {})); // safe from throwing
consolelog(12,()=> myProp in {prop:undefined}); // true (prop key exists even though its value undefined)
// beware of 'hasOwnProperty' pitfalls
// it can't detect inherited properties and 'hasOwnProperty' is itself inherited
// also comparatively verbose
consolelog(13,()=> obj.hasOwnProperty("hasOwnProperty")); // DANGER: it yields false
consolelog(14,()=> nothing.hasOwnProperty("hasOwnProperty")); // throws when undefined
obj.hasOwnProperty = ()=>true; // someone could overwrite it
consolelog(15,()=> obj.hasOwnProperty(nothing)); // DANGER: the foolish overwrite will now always return true
consolelog(16,()=> Object.prototype.hasOwnProperty.call(obj,"hasOwnProperty")); //😭 explain?!
consolelog(17,()=> Object.hasOwn(obj,"hasOwnProperty")); //😭 explain?!
function consolelog(num,myTest){
try{
console.log(num,myTest());
}
catch(e){
console.log(num,'throws',e.message);
}
}
You can use hasOwnProperty() as well as in operator.
Using the new Object.hasOwn method is another alternative and it's intention is to replace the Object.hasOwnProperty method.
This static method returns true if the specified object has the indicated property as its own property or false if the property is inherited or does not exist on that object.
Please not that you must check the Browser compatibility table carefully before using this in production since it's still considered an experimental technology and is not fully supported yet by all browsers (soon to be though)
var myObj = {};
myObj.myProp = "exists";
if (Object.hasOwn(myObj, 'myProp')){
alert("yes, i have that property");
}
More about Object.hasOwn - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn
Object.hasOwn browser compatibility - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility
Several ways to check if an object property exists.
const dog = { name: "Spot" }
if (dog.name) console.log("Yay 1"); // Prints.
if (dog.sex) console.log("Yay 2"); // Doesn't print.
if ("name" in dog) console.log("Yay 3"); // Prints.
if ("sex" in dog) console.log("Yay 4"); // Doesn't print.
if (dog.hasOwnProperty("name")) console.log("Yay 5"); // Prints.
if (dog.hasOwnProperty("sex")) console.log("Yay 6"); // Doesn't print, but prints undefined.
Working for me.
if (typeof receviedData?.d?.heartbeat_interval != "undefined") {
}
In the answers I didn't see the !! truthiness check.
if (!!myObj.myProp) //Do something

Javascript - Shorthand notation to safely check/access a property on a potential undefined object

What's the shortest syntax to check if jsonObject is not undefined before accessing its errorMessage property?
var jsonObject = SomeMethodReturningAnObject();
if (jsonObject.errorMessage === undefined) // jsonObject can be undefined and this will throw an error
/* success! */
else
alert(jsonObject.errorMessage);
You can use the && operator, since it doesn't evaluate the right-hand side if the left-hand side is undefined:
if (jsonObject && jsonObject.errorMessage === undefined)
Another way to do this is to use the typeof operator.
In JS if a variable has been declared but not set a value, such as:
var x;
Then x is set to undefined so you can check for it easily by:
if(x) //x is defined
if(!x) //x is undefined
However if you try to do if(x) on a variable that hasn't even been declared, you'll get the error you allude to in your post, "ReferenceError: x is not defined".
In this case we need to use typeof - MSDN Docs - to check.
So in your case something like:
if(typeof jsonObject !== "undefined") {
//jsonObject is set
if(jsonObject.errorMessage) {
//jsonObject set, errorMessage also set
} else {
//jsonObject set, no errorMessage!
}
} else {
//jsonObject didn't get set
}
This works because if you have a variable set to an empty object, x={}, and try to get at a variable within that object that doesn't exist, eg x.y, you get undefined returned, you don't get a ReferenceError.
Be aware that the typeof operator returns a string denoting the variable type, not the type itself. So it would return "undefined" not undefined.
Also, this very similar question on SO that could help you: How to check a not-defined variable in JavaScript
Hope this helps.
Jack.
var jsonObject = SomeMethodReturningAnObject();
if (jsonObject && jsonObject.errorMessage === undefined)
/* success! */
else
alert(!jsonObject ? "jsonObject not defined" : jsonObject.errorMessage);
if(jsonObject)
{
if (!jsonObject.errorMessage)
// success..
foo()
else
alert(jsonObject.errorMessage);
}
I'll answer the shorthand notation aspect as your specific situation is better served by an existing answer. As of ECMAScript 2018 we have spread syntax, which makes the whole thing much more concise:
if ( {...jsonObject}.errorMessage ) {
// we have errorMessage
} else {
// either jsonObject or jsonObject.errorMessage are undefined / falsey
// in either case, we don't get an exception
}
A straight if / else is not the perfect fit for your situation because you actually have 3 states, 2 of which are crammed into the same if branch above.
No jsonObject: Failure
Has jsonObject, has no errorMessage: Success
Has jsonObject, has errorMessage: Failure
Why this works:
Accessing a property foo from an object obj, assuming the object is undefined, is essentially doing this:
undefined.foo //exception, obviously
Spread syntax copies properties to a new object, so you end up with an object no matter what:
typeof {...undefined} === 'object'
So by spreading obj you avoid operating directly on a potentially undefined variable.
Some more examples:
({...undefined}).foo // === undefined, no exception thrown
({...{'foo': 'bar'}}).foo // === 'bar'

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

Categories