JavaScript console log variable and string | Example code

  • by

There are many ways to print variables and strings using the JavaScript console log function. Console log cane takes multiple arguments.

Method 1:

console.log("story", name, "story");

Benefit: if the name is a JSON object, it will not be printed as "story" [object Object] "story"

Method 2:

console.log("story " + name + " story");

Method 3: When using ES6 as mentioned above

console.log(`story ${name} story`);

Benefit: No need for extra, or +

Method 4: %

console.log('story %s story',name);

Benefit: the string becomes more readable.

JavaScript console log variable and string

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    var name = "The Mountain"
    
    console.log("story", name, "story");

    console.log("story " + name + " story");

    console.log(`story ${name} story`);

    console.log('story %s story',name);

  </script>

</body>
</html>

Output:

JavaScript console log variable and string

console.log(message) usage is simple: the argument message is logged to console.

console.log('My message');// logs "My message"

const myVar = 12;
console.log(myVar);// logs 12

Do comment if you have any doubts or suggestions on this JS console 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

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.