简体   繁体   中英

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.

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"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM