Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is the javascript console.log()?
2.1.
Syntax
2.2.
Parameters:
2.3.
Return value:
2.4.
Code
2.5.
Javascript
2.5.1.
Output
3.
Output a Variable
3.1.
Code
3.1.1.
Output
3.2.
Explanation
4.
Output an Object
4.1.
Code
4.2.
Javascript
4.2.1.
Output
4.3.
Explanation
5.
Output a String
5.1.
Code
5.2.
Javascript
5.3.
Output
5.4.
Explanation
6.
Output an Array
6.1.
Code
6.2.
Javascript
6.3.
Output
6.4.
Explanation
7.
Output a Boolean Value
7.1.
Code
7.2.
Javascript
7.3.
Output
7.4.
Explanation
8.
Output a Function
8.1.
Code
8.2.
Javascript
8.3.
Output
8.4.
Explanation
9.
Console Error in JavaScript
9.1.
Code
9.2.
Javascript
9.3.
Output
9.4.
Explanation
10.
Console Table in JavaScript
10.1.
Code
10.2.
Javascript
10.2.1.
Output
10.3.
Explanation
11.
Console Assert in JavaScript
11.1.
Code
11.2.
Javascript
11.3.
Output
11.4.
Explanation
12.
Console Time in JavaScript
12.1.
Code
12.2.
Javascript
12.3.
Output
12.4.
Explanation
13.
Advantages of Console Log
14.
Disadvantages of Console Log
15.
Frequently Asked Questions
15.1.
How to see JavaScript console logs?
15.2.
How to run JavaScript in console log?
15.3.
What mistakes should you avoid when using console.log()?
15.4.
How does console.log() affect performance?
15.5.
What is a JavaScript console?
15.6.
How to console log JavaScript object?
15.7.
How do I open JavaScript in the console?
15.8.
When to use the console log?
16.
Conclusion
Last Updated: Oct 4, 2024
Easy

JavaScript Console.Log() Method

Introduction

The JavaScript `console.log()` method is a powerful debugging tool that allows developers to output messages or values to the web console. It is commonly used to display variables, test code execution, and provide helpful information during development. By strategically inserting `console.log()` statements in the code, developers can track the flow of their program and identify any issues or unexpected behavior more easily. In this article, we will learn about the JavaScript console log. We will discuss its properties and how to use it in different cases.

JavaScript Console Log

What is the javascript console.log()?

The JavaScript `console.log()` is a built-in method that outputs a message or value to the web console. It is an essential debugging tool for developers, allowing them to monitor variables, test code execution, and identify issues by displaying relevant information in the console.

You can use this tool for troubleshooting in JavaScript. The console log will display information, errors, and warnings during the execution of JavaScript code. The console log shows messages to the console. Whereas console.warn() and console.error() display warnings and errors only. Before deploying your website, you can use it for testing JavaScript code and finding errors. You can also monitor network requests, performance timings, and security issues. It can output both variables and object data.

nav bar


The navigation bar will appear at the top of the console interface. This nav bar has six views.
 

  • The console will show you logs, warnings, and errors made by the console. 
     
  • The network will let you inspect network requests made by your page.
     
  •  Elements will show the HTML and CSS code for your page. 
     
  • Sources will help you browse and edit the page's JavaScript code. 
     
  • The performance will show performance data for the currently open web page. It can show how long it takes to load various web page parts or how long specific tasks take to run. 
     
  • The Memory will show how much memory your webpage takes. It can also report issues such as memory leaks.

Syntax

The syntax of console.log() method is mentioned below:

console.log(expression1, expression2, ..., expressionN);

 

Here’s a basic example of printing a message using a console.log() in JavaScript:

Parameters:

expression1, expression2, ..., expressionN: Values or expressions to be logged to the console. Multiple values can be separated by commas.

Return value:

The console.log() method does not return a value. It is used for outputting information to the console for debugging purposes.

Code

  • Javascript

Javascript

console.log('Hey, Ninjas!! Welcome to Coding Ninjas Studio Online Compiler!!');
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Output a Variable

First, declare a variable. Give it some value. Finally, print the output using console.log().

Code

let example1 = "We are learning JavaScript!";
console.log(example1);
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Explanation

We declared a variable ‘example1’. Then we printed its value.

Output an Object

First, initialize an object. Give it some value. Finally, print the output using console.log().

Code

  • Javascript

Javascript

// Declaring the object first.
const example2 = {
  name: "Ninja",
  age: 22,
  fav_languages: ["JavaScript", "C", "Python"],
  is_placed: true,
// Now make the function
  info_example2: function () {
      console.log(`Name: ${this.name}\nAge: ${this.age}\nLanguages: ${this.fav_languages.join(", ")}\nPlaced: ${this.is_placed}`);
  }
};
// Printing the output.
example2.info_example2();
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Explanation

We declared an object ‘example2’ and then gave it some values ‘name’, ‘age’, ‘fav_languages’ and ‘is_placed’. Then we defined ‘info_example2’, which prints the values using console.log().

Output a String

First, initialize a string. Give it some value. Finally, print the output using console.log().

Code

  • Javascript

Javascript

const coder_name = "Ninja";
const no_questions_solved = 180;
console.log(`My name is ${coder_name} and I have solved ${no_questions_solved} questions.`);
You can also try this code with Online Javascript Compiler
Run Code

Output

output


Explanation

We have declared a string ‘coder_name’ and a variable ‘no_of_questions_solved’. Then we used console.log() to print the entire message.

Output an Array

Initialize an array. Give it some value. Finally, print the output using console.log().

Code

  • Javascript

Javascript

// First declare an array.
const code_lang = ["Java", "C", "Kotlin", "Python", "JavaScript"];

for (let i = 0; i < code_lang.length; i++) {
  console.log(`Some programming languages are ${i + 1}: ${code_lang[i]}`);
}

// Using another function to print the entire array.
console.log("Some programming languages: " + JSON.stringify(code_lang));
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Explanation

We declared an array ‘code_lang’. Then we printed its value using a for loop. Then we used another JSON.stringify() method to print the whole array as a string.

Output a Boolean Value

Declare some variables. Give it the value of True or False. Finally, print the output using console.log().

Code

  • Javascript

Javascript

const x = 10;
const y = 5;
const example3 = x < y;
console.log(example3);
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Explanation

We declared two variables, ‘x’ and ‘y’, with values 10 and 5, respectively. Then we declared another variable, ‘example3’, which will compare x and y. Finally, we print the boolean value of ‘example3’.

Output a Function

Declare any function. Input some values in it. Finally, print the output using console.log().

Code

  • Javascript

Javascript

// declaring a function.
function sem_result(i) {
  if (i > 33) {
      console.log("Congo!! You passed..");
  }
  else {
      console.log("Sorry!! You failed :((");
  }
}

//Make some function calls.
sem_result(89);
sem_result(29); 
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Explanation

We have created a function ‘sem_result’. It will take argument i. If i is greater than 33, it will print a passed message. Otherwise, it will print failed message. 

There are many methods available for the console object in JavaScript. Now we will be discussing some of them.

Console Error in JavaScript

You can use it to indicate an error message in the console. The error message appears with a red icon in mainly. An error message means there's an issue in your code. You can use it with console.log() or console.warn(). If you will adequately handle errors using console.error(), you can write a robust JavaScript code.

Code

  • Javascript

Javascript

// Declaring the function. If j is zero, it will show the error message.
function example4(i, j) {
  if (j === 0) {
      console.error("You cannot divide this number by zero!");
      return null;
  }
// Return the quotient.
  return i/ j;
}
// Printing the output.
console.log(example4(26, 0));
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Explanation

We have first defined a function ‘example4’. It takes two arguments, i & j. It will return the quotient of i divided by j. But if you input j equal to zero, you’ll get an error message and no output.

Console Table in JavaScript

You can use it to arrange your data in the console. It has objects or arrays as its input. Each object or element of array showcases a row in the table. It helps display complex data structures. It works in a lot of modern browsers. You can use it with console.chart() and console.graph().

Code

  • Javascript

Javascript

const coders_info = [
  { id: 1090, name: "Ninja1", age: 22 },
  { id: 1234, name: "Ninja2", age: 21 }
  { id: 1345, name: "Ninja3", age: 19 }
];
console.table(coders_info);
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Explanation

We declare an array ‘coders_info’. ‘Coders_info’ have properties ‘id’, ‘name’ and ‘age’. Then we use console.table() to print data tabularly.

Console Assert in JavaScript

It asserts a specific condition is true. It takes an expression as its first parameter. It takes a message as its second parameter. You'll get an error message if the expression gives a false value. You can use it to catch issues.

Code

  • Javascript

Javascript

// Declare a function.
example5(i) {
  console.assert(typeof i === 'number', `There's an error: ${i} is not a correct input.`);
  console.assert(i > 0, `There's an error: ${i} is negative number.`);
  return Math.sqrt(i);
}
// Printing some values.
console.log(example5(-98));
console.log(example5('29'));
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Explanation

We have declared a function ‘example5’. It takes an argument i and returns the square root of i. We are using console.assert() for checking whether i is a number and whether is it negative.

Console Time in JavaScript

We use it for performance testing. We measure the time taken for the operation. It creates a timer that records the duration of a block of code. It takes a label as a string parameter. It is a unique identifier for the timer. 

Code

  • Javascript

Javascript

function example7(x) {
  console.time('The calculated sum is');
  let final_sum1 = 0;
  for (let i = 1; i <= x; i++) {
    // we are calculating the sum
      final_sum1 += i;
  }
  return final_sum1;
}
console.time('Final Sum is');
const final_sum = example7(10000000);
console.timeEnd('Final Sum is');
console.log(final_sum);
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Explanation

console.timeEnd() to stop the timer and print the time spent on the console. We declared a function 'example7'. console.time() starts the timer. We gave an argument of 10000000 to the function.

Advantages of Console Log

Here are some console.log() advantages:

  • It is easy to use.
     
  • It is excellent for debugging.
     
  • It shows the output of the code.
     
  • It is helpful for testing code.
     
  • It is widely supported.
     
  • It is helpful with other tools.
     
  • It monitors performance.

Disadvantages of Console Log

Here are some console.log() disadvantages:

  • It may be disabled.
     
  • It is time-consuming to sift through logs.
     
  • It may not work in older browsers.
     
  • It may turn frustrating with multiple contributors.
     
  • It does not provide enough context.

Frequently Asked Questions

How to see JavaScript console logs?

To see JavaScript console logs you can use console.log() method in Javascript.

How to run JavaScript in console log?

Type or paste JavaScript code directly into the console and press Enter to execute it in real-time.

What mistakes should you avoid when using console.log()?

You should log only a little information. You should not log sensitive information. Refrain from relying too much on console.log() and use proper debugging techniques.

How does console.log() affect performance?

Using console.log() can affect performance because each call adds overhead to the code working. The impact is minimal. But excessive use can make your code slower.

What is a JavaScript console?

The JavaScript console is a browser development tool that displays logs and errors, which allows developers to execute JavaScript code interactively.

How to console log JavaScript object?

To log a JavaScript object, use console.log(object); where the object is the variable containing your object.

How do I open JavaScript in the console?

To open the JavaScript console, press Ctrl+Shift+J on Windows/Linux or Cmd+Option+J on macOS in most browsers.

When to use the console log?

Use console.log() for debugging purposes to output values and track variable states or application flow during development.

 

Conclusion

In this article, we learnt a lot about JavaScript console log starting with how to open a web console. Then we explored how to output variables, strings, arrays etc, using a JavaScript console log. We also talked about other console methods. Refer to other JavaScript console log articles to improve your understanding of JavaScript.
 

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses, refer to the mock test and problems look at the interview experiences and interview bundle for placement preparations.

Happy Coding!

Live masterclass