I am appending text which is stored in a javascript variable into a div element. The issue is that the depending on the situation there may or may not be text stored in that variable. If there is not I end up with the text 'undefined' where the valid text would have been in the div.
so as an example:
htmlelement.innerhtml = '<h2>'+array.object.title+
'</h2><p>'+array.object.textField1+
'</p><p>'+array.object.textField2+
'</p><p>'+array.object.textfield3+'</p>';
This shows up in a function which will run for each object in the array. Not all of the objects have content in all 3 text fields.
So is there an easy way to prevent 'undefined from being printed?
Right now I have this before the previous line:
if (!array.object.textfield1) {
array.object.textfield1 = ' ';
}
if (!array.object.textfield2) {
array.object.textfield2 = ' ';
}
if (!array.object.textfield3) {
array.object.textfield3 = ' ';
}
But this is not a practical solution if there are a lot of variables that need to be checked.
A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .
To avoid undefined values when using or accessing the optional object properties, the basic idea is to check the property value using an if conditional statement or the optional chaining operator before accessing the object property in TypeScript.
Can you use the logical operator ||
?
array.object.textField1||''
Note: Please do take care of values like 0
or any other falsy
values .
Use "The New Idiot" answer this is here just fro an extra method.
The other answer is better because it molds the check into the logic ( a good thing!) and is better for performance.
with that said REGEX!!
htmlelement.innerText = htmlelement.innerText.replace('undefined', '');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With