If (myVar != "undefined") - javascript

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

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'); }

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)

What is the full form of an expressionless statement in javascript? [duplicate]

This question already has answers here:
Detecting an undefined object property
(50 answers)
Closed 9 years ago.
There's a syntax that Javascript adopted from C where you can perform a logical check, without checking anything:
if (foo) {
}
What is this equivalent to? Is it:
if (foo != null) { }
if (foo !== null) { }
if (typeof(foo) != 'undefined') { }
if (typeof(foo) !== 'undefined') { }
if (typeof(foo) != 'object') { }
if (typeof(foo) !== 'Object') { }
My actual motivation for asking is wanting to ensure that a member "exists" (that is to say, if it is null or undefined then it doesn't exist):
if (window.devicePixelRatio !== null)
if (window.devicePixelRatio != null)
if (!(window.devicePixelRatio == null))
if (!(window.devicePixelRatio === null))
if (!(window.devicePixelRatio == undefined))
if (!(window.devicePixelRatio === undefined))
if ((window.devicePixelRatio !== undefined))
My concern is if the member is defined, but defined to be null, in which case (as far as i'm concerned) it's not assigned.
I know that the expressionless syntax returns true for a "truthy" value. I'm less interested in a "truthy" value, as an actual value.
if (foo) {
}
"What is this equivalent to?"
It's not equivalent to any of the ones you suggested. It would be equivalent to:
if (Boolean(foo)) { }
or the same thing by using the ! operator:
if (!!foo) { }
or you could be explicit in your comparison if you really want.
if (!!foo === true) { }
"My actual motivation for asking is wanting to ensure that a member "exists"..."
To find if a member exists in an object, use the in operator.
if ("devicePixelRatio" in window) { }
"... (that is to say, if it is null or undefined then it doesn't exist):"
To check for not null or undefined, which is no the same as not existing, do this:
if (window.devicePixelRatio != null) { }
The != operator will perform both a null and undefined check at the same time. Any other value will meet the condition.

javascript testing for object property

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.

Checking undefined value not working?

I have the following javascript code:
var currentIds = localStorage.getItem('currentPairsIds');
if ((typeof currentIds === "undefined") ||
(currentIds == null))
$.myNameSpace.currentIDs = new Array(3);
else
$.myNameSpace.currentIDs = currentIds.Split(',');
I'm debugging with Firebug and although currentIds hasn't got any value it always executes else statement.
UPDATE: I'm getting this value from HTML5 storage.
What am I doing wrong?
This is how I have solved my problem:
var currentIds = localStorage.getItem('currentPairsIds');
if ((currentIds === undefined) ||
(currentIds == null) || (currentIds == "undefined"))
$.myNameSpace.currentIDs = new Array(3);
else
$.myNameSpace.currentIDs = currentIds.split(',');
localStorage.getItem('currentPairsIds'); returns the string "undefined".
There is another error in Split() function. The right version is without any capital letter.
I would use a direct comparison instead of the notoriously odd "typeof" operator:
if ((currentIds === undefined) || (currentIds === null)) {
//...
It's not working because localStorage.getItem returns null if the item is not defined, it does not return undefined http://dev.w3.org/html5/webstorage/#dom-storage-getitem
Example: http://jsfiddle.net/mendesjuan/Rsu8N/1/
var notStored = localStorage.getItem('ffff');
alert(notStored); // null
alert(typeof notStored); // object, yes, null is an object.
Therefore you should just be testing
alert(notStored === null);
I think you have to make checking for undefined comparing with == instead of ===.
Example:
typeof currentIds == "undefined"
This will make sure, the variable is really undefined or not.
[Edit Edit Edit Edit :P]
currentIds = "undefined"
implies
typeof currentIds == "String"
Also see, Detecting Undefined, === isn't necessary for string comparison.
In my case LocalStorage.getItem() was converting it to "undefined" as string.
I also needed to check if it s "undefined" as a string.
var myItem = LocalStorage.getItem('myItem');
if(myItem != "undefined" && myItem != undefined && myItem != null){
...
}
if( typeof(varName) != "undefined" && varName !== null )
be sure, you use ( " " ) quotes when checking with typeof()

Categories

Resources