Open In App

How to Print a String in JavaScript ?

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Javascript




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.

HTML




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


Output:

gees

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.

HTML




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


Output:

helo

Alert message



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads