Understanding Why console.log() Returns the Function Instead of a Value in JavaScript

preview_player
Показать описание
---

If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---

As a newcomer to JavaScript, you may stumble upon some quirks that initially seem confusing. One such occurrence is when you call a function and then log it to the console, only to find that the output is the function itself rather than its return value. In this guide, we'll explore this phenomenon using a practical example and clarify how function calls work in JavaScript.

The Scenario: Creating a Username

Consider the following object in JavaScript that represents a user account:

[[See Video to Reveal this Text or Code Snippet]]

You want to generate a username from the owner's name. Here's your function that performs this task:

[[See Video to Reveal this Text or Code Snippet]]

Now, if you attempt to log the function directly like this:

[[See Video to Reveal this Text or Code Snippet]]

You'll notice that the console displays the function itself rather than the username. This leads to the question: Why does this happen?

Understanding Function Execution vs. Function Reference

Function Reference

Function Execution

However, when you execute the function like this:

[[See Video to Reveal this Text or Code Snippet]]

Here’s what’s happening:

Function Invocation: The parentheses () indicate that you want to execute the function, rather than just reference it.

Return Value: The function runs and produces a result, which is the generated username.

Output: Since you are logging the result of the function, you see the expected output, "pr".

Storing Results for Clarity

If you prefer clarity, you can also store the result in a variable before logging it:

[[See Video to Reveal this Text or Code Snippet]]

This way, you explicitly assign the output of the function to result and then log that variable to the console.

Conclusion

Mastering the distinction between function references and function invocations is crucial for any JavaScript developer. When you see a function in the console without parentheses, remember you're simply referencing the function, whereas adding parentheses means you're executing it and hopefully understanding the result it gives you.

Embrace these nuances, and they'll soon become a natural part of your JavaScript programming journey!
Рекомендации по теме
join shbcf.ru