Mastering JavaScript Console Methods 2024

stsmall507x507 | Web Design | SEO | Digital Agency | McGawn DESIGNS

console.log()

console.log() is the most commonly used method for logging. It displays the output for any JavaScript code.

Example:

var firstName = "John";
console.log(firstName);  // Outputs: John

Output:
John

console.info()

console.info() is a method used to display informational messages in the console. It is primarily used for debugging and providing additional information about the execution of your code.

Example:

const firstName = "John";
const age = 25;

console.info("User Information:");
console.info("Name:", firstName);
console.info("Age:", age);

Output:
User Information:
Name: John
Age: 25

console.warn()

console.warn() is used to display warning messages in the console. It is used to alert developers about potential issues or problematic code.

Example:

const temperature = 40;

if (temperature > 30) {
console.warn("High temperature alert!");
console.warn("Take necessary precautions.");
}

Output:
High temperature alert!
Take necessary precautions.

console.error()

console.error() is used to display error messages in the console. It indicates that a critical error has occurred in the code.

Example:

function divideNumbers(a, b) {
if (b === 0) {
console.error("Error: Division by zero is not allowed!");
return;
}

return a / b;
}

console.log(divideNumbers(10, 2)); // Output: 5
console.log(divideNumbers(8, 0)); // Output: undefined

Output:

5
Error: Division by zero is not allowed!
undefined

console.clear()

console.clear() is used to clear the console, removing all previous log messages, warnings, errors, and any other output.

Example:

console.log("This is a log message.");
console.warn("This is a warning message.");
console.error("This is an error message.");

console.clear();

console.log("Cleared console. New log message.");

Output (after clearing):
Cleared console. New log message.

console.assert()

console.assert() is used to check if a given condition is true. If the condition is false, it will display an error message in the console.

Example:

function calculateSum(a, b) {
console.assert(typeof a === 'number' && typeof b === 'number', 'Both arguments must be numbers.');
return a + b;
}

console.log(calculateSum(2, 3)); // Output: 5
console.log(calculateSum(4, '5')); // Assertion error: Both arguments must be numbers.

Output:

5
Assertion failed: Both arguments must be numbers.

console.count()

console.count() is used to count the number of times it has been called at a specific point in your code.

Example:

function processItem(item) {
console.count('Item Processed');
// Code to process the item
}

processItem('A'); // Output: Item Processed: 1
processItem('B'); // Output: Item Processed: 2
processItem('C'); // Output: Item Processed: 3
processItem('A'); // Output: Item Processed: 4
processItem('C'); // Output: Item Processed: 5

Output:

Item Processed: 1
Item Processed: 2
Item Processed: 3
Item Processed: 4
Item Processed: 5

console.dir()

console.dir() is used to display an interactive listing of the properties of a specified JavaScript object.

Example:

const person = {
name: 'John Doe',
age: 30,
email: '[email protected]',
address: {
street: '123 Main St',
city: 'New York',
country: 'USA'
}
};

console.dir(person);

Output:

{name: 'John Doe', age: 30, email: '[email protected]', address: {…}}

console.table()

console.table() is used to display tabular data in the console.

Example:

const fruits = [
{ name: "Apple", color: "Red", price: 0.5 },
{ name: "Banana", color: "Yellow", price: 0.25 },
{ name: "Orange", color: "Orange", price: 0.35 },
];

console.table(fruits);

Output:
┌─────────┬─────────┬──────────┬───────┐
│ (index) │ name │ color │ price │
├─────────┼─────────┼──────────┼───────┤
│ 0 │ 'Apple' │ 'Red' │ 0.5 │
│ 1 │ 'Banana'│ 'Yellow' │ 0.25 │
│ 2 │ 'Orange'│ 'Orange' │ 0.35 │
└─────────┴─────────┴──────────┴───────┘

console.time() & console.timeEnd()

console.time() and console.timeEnd() are used to measure the time it takes for a particular operation or section of code to execute.

Example:

console.time("myTimer"); // Start the timer with the label "myTimer"

// Perform some time-consuming operation
for (let i = 0; i < 1000000; i++) {
  // Some code here
}

console.timeEnd("myTimer"); // Stop the timer and log the elapsed time

Output:
myTimer: 12.345ms (time may vary)

console.trace()

console.trace() is used to print a stack trace to the console, showing the function calls and the sequence of execution.

Example:

function outerFunction() {
  middleFunction();
}

function middleFunction() {
  innerFunction();
}

function innerFunction() {
  console.trace();
}

outerFunction();

Output:
console.trace
at innerFunction (script.js:8)
at middleFunction (script.js:4)
at outerFunction (script.js:2)
at <anonymous>:1:1

console.group() & console.groupEnd()

console.group() and console.groupEnd() are used to group console log outputs together, providing a more organised and hierarchical structure.

Example:

console.group('Group 1');
console.log('Log 1');
console.log('Log 2');
console.groupEnd();

console.group('Group 2');
console.log('Log 3');
console.log('Log 4');
console.groupEnd();

Output:
Group 1
Log 1
Log 2
Group 2
Log 3
Log 4

Each of these methods provides a different way to output information to the JavaScript console, giving developers a lot of control over how messages are displayed. They can be essential tools when testing and debugging JavaScript code.

Cookie Policy | Privacy Policy