I have some calls to AJAX where I return a JSON object as a response. This JSON object always has the same structure. However, there are sometimes where if the PHP scripts fails, some of the objects of the JSON structure are not defined or even inexistent.
This also happens with some "global" variables that are present in a page and I use in some JS files, but then go to another page where I use those JS files and the variable is not even written.
So, I thought to create a function is_defined() to which I could ask if a variable is defined or not. The function is as the following:
function is_defined(ob, can_empty){
if(can_empty === undefined || can_empty == '') can_empty = false
return ob !== undefined && ob !== null && (ob !== '' || can_empty)
}
So, if the variable passed is NULL or undefined, or it's empty (and it cannot be empty), I return false.
My problem comes when the variable is not even written, as I cannot pass it to the function because an Uncaught ReferenceError: obj is not defined error is raised.
So my question is if is there any way to create a function to check if a variable exists and is defined, as I'd like to centralize all these checks into a function and not writing obj !== undefined || obj !== null every now and then on my code.
I thought that with a double Not operator (!!!obj) would cast to false, but I face the same problem if the variable is not written.
EDIT: Just as an aclaration, the issue here is to be able to do the checks for undeclared and undefined variables inside a function, so I can pass a variable to the function without having to check it before calling it if the variable is declared or not.
Thank you all for your time and answers!
Kind regards!