JavaScript I/O Methods

Input/Output Methods in JavaScript.

JavaScript

I/O Methods

In JavaScript, basic input/output (I/O) methods can be performed using various techniques depending on the environment in which your JavaScript code is running. Below are some common methods for basic input/output operations:

1. Console Input/Output:

Input: Reading input from the console can be done using the 'prompt()' function, which prompts the user for input.

Output: Displaying output to the console is done using 'console.log()', which outputs the provided content to the console.

Example:

js Copy Code
let name = prompt("Enter your name:"); // Input
console.log("Hello, " + name + "!"); // Output
Output:
Enter your name:Ayan
Hello, Ayan!

2. Alerts:

Output: You can display alerts to the user using the 'alert()' function.

alert("This is an alert!");

If you run this code in a web browser's console or in a JavaScript environment, you'll see a pop-up alert with the message "This is an alert!".

3. HTML Input/Output:

Input: For web-based JavaScript, you can use HTML elements like '<input>' to get user input.

Output: Similarly, you can output content to HTML elements such as '<div>' or '<p>'.

js Copy Code
<!DOCTYPE html>
<html>
<body>

<input type="text" id="nameInput">
<button onclick="sayHello()">Say Hello</button>
<div id="output"></div>

<script>
function sayHello() {
    let name = document.getElementById("nameInput").value;
    document.getElementById("output").innerText = "Hello, " + name + "!";
}
</script>

</body>
</html>

Explaintion:

This HTML code defines a simple webpage with an input field, a button, and a '<div>' element for output. When the button is clicked, it triggers the 'sayHello()' function, which retrieves the value entered in the input field, concatenates it with the string "Hello, ", and then displays the result in the '<div>' element.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.