Input and Output in JavaScript
JavaScript models the HTML/XHTML document as the document object and the browser window which displays the HTML/XHTML document as the window object. The document object contains a method named write to output text and data on to the document as shown below:
document.write(“Welcome to JavaScript”);
To display multiple lines of text using the write method, include the HTML tag <br /> as a part of the string parameter as shown below:
document.write(“Welcome<br />to<br />JavaScript”);
The output of the above code on the document will be as shown below:
Welcome
to
JavaScript
Although the document object has another method named writeln which appends a new line (\n), the output of both write and writeln will be same as the browser ignores the new line characters.
The window object is the default object in JavaScript. So, whenever a property or method on window object is to be referenced, there is no need to mention window object explicitly.
There are three methods available on the window object to perform input/output namely alert and confirm for output and prompt for input. The alert method is used to display a dialog box which shows the provided text or data as output along with a OK button. The alert method can be used as shown below:
alert(“Sum of 10 and 20 is: ” + (10 + 20));
The alert method allows the new line character (\n) for displaying text in multiple lines and does not support HTML tags like <br /> etc.
The confirm method displays a dialog box which displays the string provided as output along with two buttons labelled OK and Cancel. This method returns a Boolean value true when the user clicks OK button and false when user clicks Cancel button. The confirm method can be used as shown below:
var status = confirm(“Do you want to proceed?”);
The prompt method is used to accept string input from the user. This accepts two parameters. First parameter is a string that will be displayed on the dialog box and the second string is the default input string in case the user doesn’t provide any input. The prompt method displays a string along with a textbox and two buttons labelled OK and Cancel. Prompt box can be created as shown below:
var a = prompt(“Enter a value: “, “default”);
Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Leave a Reply