Which way should be used for null comparison in JavaScript - 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'); }

Related

How to check if the datatype of an object value is null (JS)

Some values of my object are sometimes not in the domain and thus have a null value. How can I filter out the null values from this object when trying to iterate through it?
That's the code I wrote but it doesnt do anything.
function enLanguage(){
let value1 = Object.values(dicEnglish);
let key1 = Object.keys(dicEnglish);
for (let y=0; y<50; y++){
if ((typeof key1[y] === "object") || (typeof value1[y] ==="object")){
continue;
}else{
let text1 = value1[y];
document.getElementById(key1[y]).textContent = text1;
key1[y].textContent=value1[y]}}}
A couple points to notice:
In JS an object key cannot be another object.
So this typeof key1[y] === "object" is not going to work.
You would probably want Object.entries function, example:
for (const [key, value] of Object.entries(dicEnglish)) {
// Do something
}
To check if a value is nullish you can use value == null (note 2 equal signs).
This returns true if a value is null or undefined.
Given said, you can rewrite your function as:
function enLanguage(){
for (const [key, value] of Object.entries(dicEnglish)) {
// Here you check for null
if (value == null) {
// Do something
} else {
// Do something else
}
}
strangely enough, the null datatype in JavaScript is also an object.
but we can filter it out through the ! operator.
for example:
console.log(!null) // true
console.log(!undefined) // true
const x = "Hello World!"
console.log(!x) // false
it returns true if the subsequent value is null, undefined or 0 (falsy values)
so in your code change the condition:
if (!key1[y] || !value1[y]) continue
this will now skip any falsy values
A compact way to check if a value is null is trwar using strict equality operators:
(value === null) // true if value is of datatype NULL
(value !== null) // true if value is not of datatype NULL
Non-strict operators provide a similar test but check if a value is null or undefined:
(value == null) // true if value is of datatype NULL or UNDEFINED
(value != null) // true if value is not of datatype NULL or UNDEFINED.
where "NULL" mean the data type of null and "UNDEFINED" means the data type of undefined.
The typeof operator returns "function" for function objects (of data type OBJECT) and "object" for the null primitive of type NULL. This dates back to the original design and implementation of JavaScript on PC's of the 1990s era, and is so entrenched it can't be changed.
TL;DR That typeof null returns "object" does not mean null is an object or has data type OBJECT. null is the singleton value of JavaScript data type NULL.

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

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

How can I determine that an object is "custom" in Javascript?

To clarify my title, I need a way to determine that an object is not a String, Number, Boolean, or any other predefined JavaScript object. One method that comes to mind is this:
if(!typeof myCustomObj == "string" && !typeof myCustomObj == "number" && !typeof myCustomObj == "boolean") {
I could check to see if myCustomObj is an object, like this:
if(typeof myCustomObj == "object") {
This only works for primitive values, though, as this typeof new String("hello world") == "object") is true.
What is a reliable way to determine whether or not an object is not a predefined JavaScript object?
Here's is how jQuery does it in jQuery.isPlainObject()
function (obj) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if (!obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow(obj)) {
return false;
}
try {
// Not own constructor property must be Object
if (obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
return false;
}
} catch(e) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for (key in obj) {}
return key === undefined || hasOwn.call(obj, key);
}
You can use the "toString" functon on the Object prototype:
var typ = Object.prototype.toString.call( someTestObject );
That gives answers like "[object String]" or "[object Date]" for the built-in types. Unfortunately you can't distinguish that way between things created as plain Object instances and things made with a constructor, but in a sense those things aren't really that much different anyway.

Categories

Resources