Home > database >  How to NOT show Undefined when not assign value
How to NOT show Undefined when not assign value

Time:12-18

I have this function in JavaScript

function person(settings) {
  console.log(settings.name);
  console.log(settings.age);
}

And I assigned value to the function :

function({
  name: `Nana`,
});

The result are

Nana
Undefined 

I just want to skip to assign value to age and also I don't want to get undefined I want to get the result only Nana

What should I do?

CodePudding user response:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
function person(settings) {
 result = '';
   if(settings.name!=undefined) {
    result  = settings.name;
    }
    result  = ' ';
   if(settings.age!=undefined) {
        result =settings.age;
    }

    
    alert(result);
}
</script>
</head>
<body>

<h1>This is a Heading</h1>
<p onclick="person({
  name: `Nana`
});">Click Here</p>

</body>
</html>

how to and test video

CodePudding user response:

Your function print both, so you see the undefined one. You can use if statement to print only if it is not undefined.

function person(settings) {
   if (settings.name != undefined) console.log(settings.name); 
   if (settings.age != undefined) console.log(settings.age);
}

also you can use:

function person(settings) {
   if (settings.name) console.log(settings.name); 
   if (settings.age) console.log(settings.age);
}

this work because any javascript value can be convert to a boolean value, and the folowing values convert to 'false':

undefined
null
0
-0
NaN
""  // the empty string
  • Related