Skip to content

Console.log JavaScript example | Code

  • by

The JavaScript console log() is a function that writes a message to log on to the console. It is used by the web developer for debugging the app.

Log message will not display anything on the screen. It logs a message to a debugging console.

console.log("Hello");

Console.log JavaScript example

Simple example code of console.log() function in JavaScript use to print variables.

<!DOCTYPE html>
<html>
<body>

  <script>

    var num = 1000;
    console.log(num);

    var str = "Hello World!"
    console.log(str);

  </script>

</body>
</html> 

Output:

Console log JavaScript example

Passing a function as an argument:

<script>

    function func() { 
      return (5 * 10); 
    }
    console.log(func());

</script>

Passing a number with the message as an argument

<script>
   var num = 2;
   console.log("The value of num is " + num);
</script>

Passing a string with the message as an argument

<script>
    var str = "Hello";
    console.log("The value of str is " + str);
</script>

Write an object to the console:

const myObj = {firstname:"John", lastname:"Doe"};
console.log(myObj); 

Write an array to the console:

const myArr = ["A", "B", "C", "D"];
console.log(myArr);

Print a Sentence

console.log("I love JS");

Multiple Values

Instead of typing console.log() three times we can include them all.

let x = 1
let y = 2
let z = 3
console.log("x:", x, "y:", y, "z:", z)

Variables within the log

In this example, %s refers to a string option included after the initial value. The %d refers to a digit option included after the initial value.

console.log("%s is %d years old.", "John", 29)

Variations of logs

There are a few variations of logs.

console.log('Console Log')
console.info('Console Info')
console.debug('Console Debug')
console.warn('Console Warn')
console.error('Console Error')

Do comment if you have any doubts or suggestions on this JS console log topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading