Skip to content
Advertisement

JavaScript Console.log() method is outputting the function before the text given inside it

I am new to JavaScript and was facing this error when I have executed the following code. I have created a class and was trying to use it to create objects from it.

  1. Computer.js
JavaScript
  1. Script.js
JavaScript
  1. index.html
JavaScript

[This is the output I have obtained][1] [1]: https://i.stack.imgur.com/8afX0.png

Why is the myComp.outputConsole() being displayed before the "Output the methodn" in the code console.log("Output the methodn", myComp.outputConsole());? Please give me assistance about where i am going wrong. Thanks in advance!! :).

Advertisement

Answer

That happens because your method is calling console.log inside it.

When you call it on this line

JavaScript

The external console.log must execute myComp.outputConsole() before it executes itself. The text inside the outputConsole method is shown before the text “Method output” because myComp.outputConsole() does not return anything and executes an internal console.log. Once the method is resolved, console.log(“Method output”) is executed.

To obtain the expected result you could simply separate the console logs.

JavaScript

Or you can change your method to return a string

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement