The Console.log() method in JavaScript is displaying the function's output prior to the text enclosed within it

Recently delving into JavaScript, I encountered an error while running the code below. I attempted to create a class and instantiate objects from it.

  1. Computer.js
  constructor(
    // defining parameters
    name,
    modelName,
    sizeInInches,
    color,
    type,
    generation,
    clockSpeed,
    ramSize,
    diskSize,
    diskType
  ) {
    // defining properties
    this.name = name;
    this.modelName = modelName;
    this.sizeInInches = sizeInInches;
    this.color = color;
    this.type = type;
    this.processorSpecs = {
      generation: generation,
      clockSpeed: clockSpeed,
      type: type,
    };
    this.ramSize = ramSize;
    this.diskType = diskType;
    this.diskSize = diskSize;
  }
  
  outputConsole() {
    console.log(this.name, this.ramSize, this.color, this.diskSize);
  }
}

export default Computer;
  1. Script.js
import Computer from "./Computer.js";

const myComp = new Computer(
  "Pranav's HP Laptop",
  "HP-envym6-1225dx",
  15,
  "Grey",
  "Intel i5",
  "3rd-Generation",
  "2.2GHz",
  "8.0 GB",
  "HDD",
  "750.0 GB"
);

console.log("Object created\n", myComp);
console.log("Method output\n", myComp.outputConsole());
console.log("Program Finished");
  1. index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Practice: Making classes and objects</title>
    <script type="module" src="Computer.js"></script>
    <script type="module" src="script.js"></script>
  </head>
  <body></body>
</html>

[Viewing the obtained output][1] [1]: https://i.sstatic.net/8afX0.png

Why is myComp.outputConsole() displayed before "Output the method\n" in the line

console.log("Output the method\n", myComp.outputConsole());
? Please guide me on where I might be mistaken. Thanks in advance! :)

Answer №1

It occurs because the method includes a console.log statement within it.

When you call it at this specific line

console.log("Method output", myComp.outputConsole());

The external console.log needs to run myComp.outputConsole() before displaying its own message. The content inside the outputConsole method appears first since myComp.outputConsole() does not return anything and includes an internal console.log. Once the method is resolved, console.log("Method output") then displays.

To achieve the desired outcome, you can separate the console logs like so:

console.log("Method output")
myComp.outputConsole(); // this will also be printed due to the internal console.log implementation

Alternatively, you can modify your method to return a string:

  outputConsole() {
    return this.name +""+ this.ramSize +""+ this.color +""+ this.diskSize;
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Halting execution: Trying to use the keyword 'import' which is not allowed here

0. April 2023: error cannot be reproduced anymore see here The error is no longer replicable due to bug fixes in react-scripts 5.0.1. 1 Even though the error is gone, the question and my self-answer still seem relevant to Angular users and others as we ...

Alternative Approaches for Assigning Parameters to app.use()

Is there a distinction between the following? app.use('my-directory', express.static(join(__dirname, 'my-directory')); and app.use(express.static(join(__dirname, 'other-directory')); It seems like they have similar functio ...

struggling with aligning elements vertically in Bootstrap

Is there a way to ensure all the grid elements in a row have the same height without explicitly setting it? I tried using align-item-stretch but the arrow button is not adjusting as desired. Any suggestions on how to align the arrows at the same height? ...

Using Angular variables in Laravel blade can add dynamic data and functionality to your web

Just starting out with Angular Js and I'm encountering an issue when trying to use an angular variable in a blade file. The error message I'm getting is: Use of undefined constant count - assumed 'count' (View: C:\xampp\htd ...

How can one access the precise and straightforward code for implementing the Facebook pixel?

(I am continuously refining this question, feel free to help me articulate it better. I have provided my own answer to assist in framing the question more effectively) Explicit - in this context, means "direct". The code provided by Facebook is minified a ...

An innovative approach to creating reusable data visualization using Angularjs?

I am seeking to create a reusable SVG chart using Angularjs and I have some inquiries regarding directives and controllers. Initially, I would like the markup to look something like this, rendering a chart with form elements that impact the internal state ...

Load JQuery into a specific div by specifying the div in the data attribute of the link

I've been searching for a solution, but haven't found it yet. I'm looking to use jQuery load to load a page when clicking on a link with the "rel" attribute. However, I want the script to locate the data in the clicked link and update the di ...

Glitch in JavaScript: Converting Text to Numbers

My current challenge involves converting text into numbers using code. Here is the code snippet I have: var vals= ["a","b","c","d","e","f","g","h","i","j", ...

Send information to the webpage through both GET and POST methods

Can data be submitted to the same page using both the GET and POST methods? Certain sensitive information needs to be sent via POST, while other data such as page_number and search_phrase should be submitted with GET. I attempted creating two forms, one ...

Attempting to spread a non-iterable instance is invalid. For non-array objects to be iterable, they must have a [Symbol.iterator]() method

data(){ return { tables:[] } }, mounted(){ this.fetchData() }, methods:{ fetchData(){ var subscription = web3.eth.subscribe('logs', { address: '0x123456..', topics: ['0x12345. ...

Navigating the art of employing different fonts for a website

I am looking to incorporate the trainway font into my website, but I'm concerned that the user may not have it installed on their device. Is there a way to showcase text in a specific font without requiring the user to download and install it? Thank ...

jquery monitors an element to see if it contains a particular attribute, then takes action accordingly

I'm attempting to conceal a div when an anchor tag (a) has a particular href, and reveal it when the href is different. This is what I've tried: if($('a[href="#intro"]').not(".active")) { $('.navbar-brand').hide();} else ...

Transferring the output of a Javascript function to display in a different location

One of the challenges I'm facing involves a function that calculates the total cost of tickets based on user selection from a dropdown list. The price per ticket is stored in my database and retrieved when needed. The function itself is functional: ...

What is the best way to organize and group messages in JavaScript in order to push them to a subarray?

Having trouble coming up with a name for this question, but here's the issue I'm facing: I currently have an array in PHP containing several entries. Array ( [0] => stdClass Object ( [sender_id] => 0 [me ...

Remove Vue Component from the styling of current application

We integrated a Vue component (using Vuetify) into our existing .NET MVC application. The issue we are facing is that the Vue component is inheriting all the CSS styles from the rest of the application. Here's a simplified version of the HTML structur ...

Exploring nested documents in mongoDB with mongoose

As a novice full stack web developer, my current project involves creating a movie rating website. To achieve this, I have set up a user schema using mongoose with a ratings subdocument. Here is an example of the schema: const ratingSchema = new mongoose. ...

The intention behind a specific line of code in React-JavaScript

I have a question about a specific line of code that I'm struggling to understand. Here is the code snippet in question: this.buttonClicked = this.buttonClicked.bind(this); Even though my program seems to be working fine without it, what exactly is ...

Converting dynamic content within a div into an interactive link

I am currently working with Longtail's JW Player and facing some difficulties with a basic function. Since I am not familiar with the programming language terminologies, I will describe the issue step by step: There is a JavaScript code that displays ...

Encountering error: Server tags are not allowed to include <% ... %> constructs

<input id="tbxPopupCode" type="text" runat="server" value="<%= Request.QueryString["code"].Replace("-"," ") %>" /> Encountering an issue: The error message states that server tags cannot contain <% … %> constructs. I am looking for ...

Positioning JQuery sliders

I've been working on a jQuery slider for my header, but I'm encountering an issue where the previous image drops down to the next container instead of staying in place and transitioning smoothly. It seems like there might be an error in my HTML/C ...