user3145047
user3145047

Reputation: 83

How to get rid of this "undefined" in javascript?

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

Answers (1)

thefourtheye
thefourtheye

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.

  1. 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.

  2. Or, simply don't log the output of greeting and simply call it like this

    greeting("name");
    

Upvotes: 6

Related Questions