Javascript - how to check if the parent object is not undefined? [duplicate] - javascript

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 5 years ago.
I find I'm doing this, whereby I need to check that the preceeding variable is not undefined before checking the next one in the chain:
if( this.props.someVar && this.props.someVar.data ) {
// do something with this.props.someVar.data ...
}
It would be ideal just to do this:
if( this.props.someVar.data ) {
// This throws an error because I haven't checked if `this.props.someVar` exists beforehand.
}
Is there an easier/shorter way to so this, preferably using pure Javascript?

I hate that too. The easiest way is to use try catch like this
try {
// do something with this.props.someVar.data
} catch (e) {
if (e instanceof TypeError) {
// TypeError happens when an object in the chain is undefined
}
}

Related

How do I prevent TypeError blank is undefined? [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 3 years ago.
Is there an easier way to check if a variable is defined or not in JavaScript when the target is deep within an object?
For example.
// Lets assume this:
response = {
status: "simple-message"
}
// running this:
if (response.data.variable_to_check !== undefined) console.log('undefined');
// will result in this:
> TypeError: response.data is undefined
In PHP I can run the equivalent check:
if (!($response->data->variable_to_check ?? false)) die("Handled Undefined Error");
// will result in this:
> Handled Undefined Error
I know I can iterate manually by checking each item starting with the root to see if it's defined, but that seems tedious. That and wrapping everything in a try/catch.
Is there a cleaner / faster / smarter way to do this?
Use
try{
if(response.data.variable_to_check!==undefined){
console.log("undefined");
}
}
catch(err){console.log(err.message)}

How can I check if a variable exists (at all) in JS? [duplicate]

This question already has answers here:
JavaScript check if variable exists (is defined/initialized)
(32 answers)
Closed 3 years ago.
Please read the question before marking duplicate. This isn't about an undefined variable. It's about variables which don't exist in the namespace.
I'm working on a codebase which is run in browser and in nativescript. The globals differ between the two. For instance, I'd like to check if window exists at all, but something like this:
if (!!window) {
}
will throw an error:
JS ERROR ReferenceError: Can't find variable: window
Is there a way to test whether or not a variable exists in js (not just undefined)?
You could use a try/catch statement.
try {
if (!!someVariable) {
console.log('yep');
}
} catch {
console.log('nope');
}
You need to use the typeof operator to see if a variable exist or no
you need to test if the variable you are concerned with is undefined of null like so :
if (typeof variable === 'undefined' || variable === null) {
// variable does not exist
}

Why does If statement throw an undefined error when I am checking if its undefined? [duplicate]

This question already has answers here:
Access Javascript nested objects safely
(14 answers)
Closed 4 years ago.
Why does my else if statement cause the parser to throw an undefined error? I know that it is undefined which is why I am checking, I want it to hit the else block in this case, because this function is used in mutiple places the data that is being passed in is not always the same. So I am trying to check which type of data is being passed in.
if(icon){
dv.find(".mobCol>.image").html(generateIcon(icon));
}
else if(location[0].properties !== undefined){
dv.find(".mobCol>.image").html(generateIcon(location[0].properties.image));
data = location[0];
}
else{
dv.find(".mobCol>.image").html(generateIcon(location.features[0].properties.image));
data = location.features[0];
}
Because location[0] is undefined. It's a bit odd, but your check should be:
if( location[0] && location[0].properties){ /* .. */}
I've omitted the ===undefined, thats not needed. It tests if it is something is thruthy or falsey
This is a common way to check variables in JS.

Prevent stop of code execution on undefined value [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 8 years ago.
Often, I write something like this:
if(model.properties.foo.bar){
// ...
}
else{
// ...
}
Currently, I want to fetch a document only if it isn't already cached. To do so, I write an if-statement like above, checking for the title of the current document.
However, if there is no current document because the user just entered my application, this check will fail due to an undefined model.properties. An error is thrown and the else block won't execute.
What is the commonly best practive to write such checks?
if(model.properties != null){
if (model.properties.foo.bar) {
// ...
} else {
// ...
}
// ...
}
else{
// ...
}

How do I check if an element is undefined? [duplicate]

This question already has answers here:
Detecting an undefined object property
(50 answers)
How can I determine if a variable is 'undefined' or 'null'?
(34 answers)
Closed 9 years ago.
I would like to check to see if a particular attribute of a DOM element is undefined - how do I do that?
I tried something like this:
if (marcamillion == undefined) {
console.log("Marcamillion is an undefined variable.");
}
ReferenceError: marcamillion is not defined
As you can see, the reference error is telling me that the variable is not defined, but my if check is clearly not working, because it is producing the standard js ReferenceError as opposed to the error message I am looking for in my console.log.
Edit 1
Or better yet, if I am trying to determine if the attribute of an element is undefined like this:
$(this).attr('value')
What would be the best way to determine if that is undefined?
Using typeof:
if (typeof marcamillion == 'undefined') {
console.log("Marcamillion is an undefined variable.");
}
Edit for the second question:
if ($(this).attr('value')) {
// code
}
else {
console.log('nope.')
}
if (typeof marcamillion === 'undefined') {
console.log("Marcamillion is an undefined variable.");
}
Note that using === instead of == is considered better style.

Categories