Generating Output in JavaScript

Explore various methods for generating output in JavaScript with clear examples. Each example shows the code and its output below.

Example 1: Using console.log() - For Debugging

This method outputs information to the console, useful for debugging or viewing data in development tools.

<!DOCTYPE html> 
<html lang="en"> 
<head> 
     <title>Document</title> 
</head> 
<body>
    <script>
        console.log("welcome to AIT!"); 
    </script> 
</body>
</html> 
          

Example 2: Using alert() - Display Alert Box

This method displays a popup alert box. It pauses code execution until the user closes the alert.

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <title>Document</title> 
</head> <body> <script>alert("This is an alert box!");
    </script> 
</body> 
</html> 
                      

Example 3: Using document.write() - Write Directly to Page

Writes content directly to the HTML document, replacing any existing content. Use sparingly, as it can overwrite the page.

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <title>Document</title> 
</head> 
<body> 
    <script> 
        document.write("Hello from document.write!");
    </script> 
</body> 
</html>
                      

Example 4: Using innerHTML - Insert Content in Element

Modifies the content of an HTML element. Ideal for displaying dynamic content within specific parts of the page.

<!DOCTYPE html>
<html lang="en"> 
<head> 
    <title>Document</title> 
</head> 
<body> 
    <div id="innerHTMLOutput"></div>
    <script>
        document.getElementById("innerHTMLOutput").innerHTML = "Content updated using innerHTML!";
    </script>
</body> 
</html> 
                      

Example 5: Using console.warn() - Display Warnings

This method outputs warnings in the console, usually styled with a yellow background for easy identification.

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <title>Document</title> 
</head> 
<body> 
    <script>
        console.warn("This is a warning message!");
    </script> 
</body> 
</html> 
                      

Example 6: Using console.error() - Display Errors

This method displays error messages in the console, usually styled in red for visibility, and useful for catching issues in code.

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <title>Document</title> 
</head>
<body> 
    <script> 
        console.error("This is an error message!");
</script> </body> </html>