How would i do the below with Javascript?
var object
function() {
return {
object: Return true if object exists or object is set to true, or false if set to false, if object doesnt exisit return false
}
}
How would i do the below with Javascript?
var object
function() {
return {
object: Return true if object exists or object is set to true, or false if set to false, if object doesnt exisit return false
}
}
Objects that do not exist are undefined
. You can compare object with undefined
to check for its existence.
Make sure to use ===
to check equality with types.
You could use instanceof to check if its an object. Typeof would return true if the object is null, because null is technically an object!
var obj = {};
var obj2 = null;
alert("Is obj a true object? "+isObject(obj));
alert("Is obj2 a true object? "+isObject(obj2));
// False positive
alert("Is obj a object? "+isObjectFalsePositive(obj));
alert("Is obj2 a object? "+isObjectFalsePositive(obj2));
function isObject(inputVar) {
return inputVar instanceof Object;
}
function isObjectFalsePositive(inputVar) {
return typeof inputVar === 'object';
}
You need to check for undefined
and false
to return value as false
. If the object
value is set to true the return flag should be true
. Below code snippet might help you.
var object;
function checkObject() {
var returnFlag;
if(typeof object == 'undefined' || !object) {
returnFlag = false;
} else if(object) {
returnFlag = true;
}
return returnFlag;
}
console.log(checkObject());
Or you can just return !!object
var object;
function checkObject() {
return !!object;
}
console.log(checkObject());