Issue
This Content is from Stack Overflow. Question asked by Faiz
Hey guys I am new to JavaScript and learning Objects in JavaScript ,
while i was printing a function value from an object the value gets printed along with a undefined value.
I was just trying to concatenate two string in a function and printing it.
I am not getting any undefined value if I just try to concatenate the string with console.log
but the issue arises when I try to concatenate through a function in a object.
let user = {
firstname:'faiz',
lastname:'mohammed',
fun : function() {
let full_name = (this.firstname + " " + this.lastname);
console.log(full_name);
},
}
console.log(user.fun());
the output is :
PS C:UsersfaizkOneDriveDesktopWEBDEVJS> node objects.js
faiz mohammed
undefined
PS C:UsersfaizkOneDriveDesktopWEBDEVJS>
when I just console log it I am not getting any undefined values :
console.log(user.firstname + " " + user.lastname);
output:
PS C:UsersfaizkOneDriveDesktopWEBDEVJS> node objects.js
faiz mohammed
PS C:UsersfaizkOneDriveDesktopWEBDEVJS>
Solution
Your fun
function doesn’t return anything so console.log(user.fun())
prints undefined
Either return something:
function() {
let full_name = (this.firstname + " " + this.lastname);
return full_name
},
console.log(user.fun());
or don’t use console.log
function() {
let full_name = (this.firstname + " " + this.lastname);
console.log(full_name);
},
user.fun();
This Question was asked in StackOverflow by Faiz and Answered by Konrad Linkowski It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.