Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptWays to Format Console Output in JavaScript

Ways to Format Console Output in JavaScript

In web development we use the browser’s console window to display messages such as errors or warnings or even personalised methods. Mostly it is used by programmers for testing and debugging process.

We can modify the console output according to our convenience to create personalised messages. We will discuss some approaches to format a console output through the examples given below.

Method 1: Using %c format specifiers.

  • Write the message in console.log() statement
  • Add %c specifier at beginning
  • Declare the styling change in CSS format
  • Print the output on console

Example 1: This example, implements the above approach

Javascript




console.log("%cWelcome to neveropen", "color:green;")


Output:

 

Example 2: This example store the CSS styling in a variable and the applies it to the message

Javascript




let style = `
    color:green;
    font-size:16px;
    background-color:black;
`
console.log("%cWelcome to neveropen", style);


Output:

 

There are some inbuilt methods of console which allow us to create personalized warnings and error messages

Method 2: Creating error and warnings messages

Example : This method implements the above approach.

Javascript




// Displaying a Warning
console.warn("This is a warning");
  
// Displaying an error
console.error("This is an error");


Output:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments