Progressive Full Stack Application Development with Live Projects

Basic Input and Output
JavaScript Lesson

Basic Input and Output

1. Output in JavaScript

a. Console Output

In JavaScript, you can use console.log() to print output to the console. This is commonly used for debugging purposes.

Example:

console.log("Hello, world!");

b. Alert Dialog

You can use alert() to display a message in a dialog box. This method is often used for simple notifications.

Example:

alert("Hello, world!");

c. Writing to the Web Page

You can use document.write() to write content directly to the web page. Note that this method is not recommended for modern web development because it can overwrite the entire document.

Example:

document.write("<h1>Hello, world!</h1>");

d. Updating the DOM

You can dynamically update the content of HTML elements using JavaScript. This method is preferred in modern web development.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>Update Content Example</title>
</head>
<body>
    <h1 id="greeting"></h1>
    <script>
        document.getElementById('greeting').textContent = "Hello, world!";
    </script>
</body>
</html>

2. Input in JavaScript

a. Prompt Dialog

You can use prompt() to get user input through a dialog box. The prompt() function returns the input value as a string.

Example:

let name = prompt("What is your name?");
console.log("Hello, " + name + "!");

b. Form Input

In web development, user input is often collected through HTML forms. JavaScript can then be used to retrieve and process this input.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>Form Input Example</title>
</head>
<body>
    <form id="myForm">
        <label for="userInput">Enter something:</label>
        <input type="text" id="userInput">
        <button type="button" onclick="processInput()">Submit</button>
    </form>

    <script>
        function processInput() {
            let userInput = document.getElementById('userInput').value;
            console.log("User entered: " + userInput);
        }
    </script>
</body>
</html>

Leave a Reply