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
- Write the error in console.error() method
- Write the warning in console.warn() method
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: