Open In App

How to Print a String in JavaScript ?

In JavaScript, printing a string means displaying the contents of a string variable or literal to the console, webpage, or any other output medium. Strings are a fundamental data type in JavaScript, representing sequences of characters enclosed within single (”) or double (“”) quotes.

Print Strings on Console

It is commonly used for debugging and logging messages to the browser console. You can check the printed string by going to the inspect element and then selecting the console tab.

Syntax:

console.log("Geeksforgeeks");

Example: The below code will explain how you can print a string in console.






console.log("Geeksforgeeks");
const desc = "A Computer Science Portal";
console.log(desc);

Output
Geeksforgeeks
A Computer Science Portal

We can use either the document.write() method or the innerHTML property to print the string on web page.

Example: The below code uses document.write() to print string on web page.




<!DOCTYPE html>
<html>
 
<body>
    <h2>Hello, GeeksforGeeks</h2>
</body>
<script>
    document.write("Hello, Geeks");
</script>
 
</html>

Output:

We can provide strings in pop up dialogue box. It can be shown using any of the alert, prompt or confirm method.

Example: The below code implements alert box to print the string in dialog box.




<!DOCTYPE html>
<html>
 
<body>
    <h2>Hello,Geeksforgeeks</h2>
</body>
<script>
    alert("Hello Geeks!");
</script>
 
</html>

Output:

Alert message


Article Tags :