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

Why the console runs "console.log(name); on line 14 first than line 12?

When you first show us the console of this file, we can see "Andrew" ion line 14 runs before Joel Kraft on line 12. I am wondering whats the reason of this.

christopher abramson
christopher abramson
22,741 Points

Give us an example of the code please, and we'll see if we can help!

<html> <head> <title>name - let and Const</title> </head> <body> <h1>Name</h1> <script> var name = "Andrew";

  function createFullName(fName, lName) {
      name = fName + " " + lName;
      console.log(name);
  }
  console.log(name);
  createFullName("Joel", "Kraft");
</script>

</body> </html>

So the above is the original code, and if you run the console you are likely see what I am confused with (I am a beginner of JS)

2 Answers

Steven Parker
Steven Parker
243,656 Points

It's the difference between declaring and calling a function.

When you declare a function, you're only telling the computer what to do later when you call that same function. It doesn't happen yet.

So the code inside the function only runs when the function is called on line 15.

You declare the variable name with the value of "Andrew" and you console log the name and then you execute the function that will print out Joel Kraft