Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Edwin Carbajal
Edwin Carbajal
4,133 Points

function result returns undefined when stored in a variable and called from a separate file

I have two javascript files, A & B. In file A I call a javascript function in File B and save its result in a variable like so:

File A

let result = someFunction();

File B

const someFunction = () => {
 // Do something here
  return Object // Returns an array
}

And then in File A, when I console.log(result) to see it's value, it returns undefined. Both of the files are added to my html as scripts before the closing body tag.

Edwin Carbajal
Edwin Carbajal
4,133 Points

Oh, and I tried console.log on the object itself in File B and it returns a value.

1 Answer

andren
andren
28,558 Points

What order are the files loaded in? Is Script A linked above script B?

It would help to actually see exactly how both the HTML and JavaScript files are setup. That would give me more details to work with, but based on your current post my assumption is that you are loading Script A before Script B.

When a browser loads a page it will run the JavaScript files in the order that they are linked, so if Script A is linked first it will run all of the code in that file before it moves on to Script B. So if the function is defined in Script B then it will not actually be created before Script A has finished, which means that it cannot be referenced in Script A.

That is also why you always have to place library scripts like jQuery above other scripts that depend on it, since it needs to be run through first.