javascript testing for object property - javascript

I have a string like this:
var TheDate = "6.14.2012";
and I have an object MyObject that has properties that may match that string. However, when I write this:
if (MyObject[TheDate] === null || MyObject[TheDate] === 'undefined') { .... }
the conditions never seem to evaluate to true even though I know the property doesn't exist.
What am I missing??
Thanks.

Existence of Own Property
If you want to check for the existence of a property use .hasownProperty()...
if (MyObject.hasOwnProperty(TheDate)) {
Existence of Own Or Inherited Property
If the property may be inherited, to test for existence use the in operator...
if (TheDate in MyObject) {
null or undefined value test for Own Or Inherited Property
If it's not existence, but rather a value test, and you want to test for null or undefined, then use this...
if (MyObject[TheDate] == null) {
This will check for both null and undefined.

The problem is with the quotes around undefined ;)
Change
if (MyObject[TheDate] === null || MyObject[TheDate] === 'undefined') { .... }
to
if (MyObject[TheDate] === null || MyObject[TheDate] === undefined) { .... }
It should work :)

If you want to use the string "undefined" rather than the undefined object, the way to do this is to check the "typeof", which returns a string. In this case, if you're looking to test if it's set to "undefined":
if ( MyObject[TheDate] === null || typeof MyObject[TheDate] === 'undefined' ) { .... }

Try the following
if ( (MyObject[TheDate] === null) || (typeof MyObject[TheDate] === 'undefined') {
....
}
You were checking whether your property contains the String 'undefined' and not whether its value is currently undefined.

Related

Which way should be used for null comparison in JavaScript

To check whether an object is null or not in javascript, i have seen two ways,
let obj = {};
Option 1
if(obj){ console.log('object exists'); }
Option 2
if(!!obj === true){ console.log('object exists'); }
Is there any advantage of choosing one option over the other? which option is preferred as the standard code ?
Use simple ===.
In your code, you are not checking if the object is null or not. Instead, your code just checks if it's not a Falsy value. Note that there are a total of 6 Falsy Values in JavaScript, null being one of those. Read more about them here. If you just want to check if a variable is null, the following is the best way to go:
if (obj === null) {
console.log("object is null");
} else {
console.log("object is not null");
}
If you only want to check if the object is null:
if(obj === null) {
...
}
An object in javascript is always truthy irrespective of whether it has any property defined on it.
Thus,
var obj={}
if(obj){
//this block will always be executed.
}
If you want to check if an object has been defined in the current lexical scope try:
if(typeof(obj) !== 'undefined' && obj !== null){
console.log('object exists');
}
else{
console.log('nope')
}
If you want to check if an object has any property on it or it is an empty object try:
if(typeof(obj) !== 'undefined' && obj !== null){
console.log('object exists');
}
else{
if(Object.keys(obj).length){
//do something
}
}
To test if a value obj is of Object data type, try
if( obj and typeof obj === "object") {
// obj is an object and it's safe to access properties
}
The truthiness of obj indicates it's not null, and typeof returning "object" means it's not some other primitive data type.
Note that null is its own data type in JavaScript (null), but typeof null returns "object" because of limitations in the early implementations of the language.
Conversely, to test if a value is null and not an object, simply use a strict equality test:
if( obj === null) {
// the data type of obj is null
...
}
Choosing a comparison method varies on how you predict how the data type will be,
but if you want a really safe standard, use 'typeof'.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
if( typeof obj === "object" ){ console.log('object exists'); }
if( typeof obj !== "undefined" ){ console.log('object exists'); }

If (myVar != "undefined")

I wanted to check whether an item in localWebstorage was not yet given a value. I tried doing this by:
//Change localStorage.intervalSetting from 'Undefined' to 'Never'
function initialIntervalSetting() {
var getValue = localStorage.intervalSetting;
if (typeof getValue === undefined) {
localStorage.intervalSetting = "option1";
alert("Changed the localWebstorage item from undefined to "option1");
}
else {
alert("JavaScript thinks that the item is not undefined");
}
}
This does not work, HOWEVER.. The question was asked here:
How to check for "undefined" in JavaScript? and someone answered:
if (typeof getValue != "undefined") {
localStorage.intervalSetting = "option1";
}
They suggested replacing === with !=
For some reason, this works- How???
Shouldn't (getValue != "undefined") return false because != means NOT EQUAL??
In your code you compared typeof getValue with the literal type undefined. Since typeof actually gives you a string, you should compare this value to the string "undefined".
Either
if (typeof getValue !== "undefined")
Or
if (getValue !== undefined)
will do the trick.
I recommend using a "truthy" check. This will check if the object is null or undefined. You can do this by just checking your getValue.
if(getValue) {
// not undefined
}
Another SO post for reference: Understanding JavaScript Truthy and Falsy

check for undefined or null

I'm checking if the value of cookie is undefined or null but weirdly this does not really work
Here's what I tried
function check(val){
if($.cookie(val) === "undefined" || $.cookie(val) === "null"){
return "1";
}
return $.cookie(val);
}
So even if my cookie has value null it would print out null instead of 1
That is because you are using quotes. In other words, "undefined" === undefined is false.
if($.cookie(val) === undefined || $.cookie(val) === null){ //this would be more apropriate
Please check if jquery cookie library is included , this is the most general cause.

How to easily check if undefined in javascript object?

Assuming I have a javascript object "myobject" that just contains an empty object "{}".
I ideally in my code I want to do the following:
if (theobject[keyvar][subkeyvar]) {
// do something
}
The issue now is that because keyvar and subkeyvar do not actually exist within the object, it fails and comains that the properties are undefined. What is the simplest/least lines of code/best way to be able to do have it just "know it is undefined" and continue to execute the //do something or not without crashing?
I dont want to get too carried away with checking like:
if( keyvar in theobject ) {
if(subkeyvar in theobject) {
if.....
}
}
if (typeof theobject[keyvar] !== "undefined" && typeof theobject[keyvar][subkeyvar] !== "undefined") {
// keyvar and subkeyvar defined
}
first we check if keyvar typeof is undefined and then if subkeyvar is undefined and if they are both defined typeof theobject[keyvar] !== "undefined" && typeof theobject[keyvar][subkeyvar] !== "undefined" is true.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
you can try this :
if (theobject[keyvar] && theobject[keyvar][subkeyvar]) {
// do something
}
If they both can possibly be undefined, you have to test one, then the other.
if (theobject[keyvar] && theobject[keyvar][subkeyvar]) {
This will of course fail on a key containing 0 or "" (or several other falsey but not undefined values) so you may want to use typeof on the second test.
Try:
if (theobject[keyvar] !== undefined && theobject[keyvar][subkeyvar] !== undefined) {
// do something
}
Since the && operator is used, the if will not check the second value if the first value is falsey, so you will never get the 'properties are undefined` error
theObject.hasOwnProperty(keyvar) && theObject.hasOwnProperty[keyvar].hasOwnProperty(subkeyvar)

comparing against undefined

Is it unsafe to compare a variable against undefined?
if(foo == undefined)
vs
if(foo == 'undefined')
Is the first example sufficient? Or should it be something like
if('undefined' in window){
//compare against undefined
} else {
//compare against 'undefined'
}
since undefined exists on the window object? Will it exist in all browsers? Or should I simply compare to == 'undefined'? I've found some similar questions on SO, but no answers regarding the existance of the undefined property on the window object.
I think you're getting mixed up between foo == undefined and typeof foo == "undefined".
Both will yield the same result unless the variable undefined has been set to something else in the current scope. In this case, foo == undefined will compare against that, where-as typeof foo == "undefined" will still resolve correctly.
var undefined = 4;
var reallyUndefined;
reallyUndefined == undefined; // false
typeof reallyUndefined == undefined; // true
Whether it's a real world scenario that undefined will ever be set to something else is debatable, and I'd question the validity of the library/ code that does that... Because of this however, it's deemed good practise to always use typeof foo === "undefined".
I'd also be wary about using foo == undefined against foo === undefined (note the triple equals, which does not use type-coercian, compared to == which does).
Using ==, you run the risk of things like null == undefined; // true, where-as null === undefined; // false. This is a good example of why you should always use ===.
tl;dr: typeof foo === "undefined";
I'd suggest you to use typeof instead:
if (typeof foo == "undefined") {
// ...
}
Note, that typeof returns a string, so you should always compare it with string value.
if (foo === undefined)
Is safe
There are several ways to do this, but the easiest I've found is this:
if(foo === undefined){
//do stuff
}
If you have complete control of all the code and you know you won't have to worry about someone mucking about with undefined then it is safe to compare against it.
alert(window.foo === undefined);
On the other hand, if you want to be a bit more paranoid, you can do a typeof check which can't be affect by the outside word
alert(typeof window.foo == 'undefined')
The third option is to have your own, local, undefined variable.
function testme(a, undefined) {
alert(a === undefined); // Will be false.
}
testme(10);

Categories

Resources