Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to prevent undefined javascript variables from displaying 'undefined' when inserted into html?

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.

like image 500
Hal Carleton Avatar asked Jul 06 '13 21:07

Hal Carleton


People also ask

Why is my JavaScript returning undefined?

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 .

How do you avoid undefined values in TypeScript?

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.


2 Answers

Can you use the logical operator || ?

array.object.textField1||''

Note: Please do take care of values like 0 or any other falsy values .

like image 154
AllTooSir Avatar answered Sep 27 '22 18:09

AllTooSir


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', '');
like image 30
raam86 Avatar answered Sep 27 '22 17:09

raam86