Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Shane McC
Shane McC
3,005 Points

Why am I returning undefined?

Hi Everyone,

I was playing around with javascript and I don't understand why I'm returning "undefined" with the syntax below. What am I doing wrong?

Thanks

var from = function(state, city, name){
console.log("Hi, I'm " + name + ". I'm from " + city + ", "+ state );
};

console.log(from("Massachusetts", "Boston","Bob"));

1 Answer

Sean T. Unwin
Sean T. Unwin
28,672 Points

It is because your function is not returning anything, but simply outputting some data to the console.

As per the ES5 [[Call]] internal method for a Function object spec (specifically points 5 and 6), if a function does not explicitly return anything it will return undefined.

One way to refactor your function would be:

var from = function(state, city, name){
  /*
   * Create a local variable, mainly to ease readability
   * and to understand what we're attempting to do
   */
  var rStr = "Hi, I'm " + name + ". I'm from " + city + ", " + state;

   /* Return the string */
  return rStr;
};
// Call your function using console.log
console.log(from("Massachusetts", "Boston", "Bob"));

I hope that helps to clarify.

Shane McC
Shane McC
3,005 Points

Thanks Sean, appreciate the help