Reputation: 83
I have following JavaScript code:
var greeting = function (name) {
console.log("Great to see you," + " " + name);
};
console.log(greeting("name"));
It printed: Great to see you, name undefined
How to get rid of this "undefined"?
Thanks.
Upvotes: 1
Views: 1766
Reputation: 239443
The undefined
is getting printed because, JavaScript functions return undefined
, by default, if we don't explicitly return anything. In your greeting
function, you are logging the string and not returning anything.
So, two ways to fix this.
Return the string from greeting
function like this
return "Great to see you, " + name;
Note: As @nnnnnn mentioned in the comments, you don't have to concatenate an extra space character. You can simply include it as part of the previous string, like shown in this answer.
Or, simply don't log the output of greeting
and simply call it like this
greeting("name");
Upvotes: 6