Java Script Built-in functions
In this tutorial you will learn how to display in-formation, take input or to get any confirmation from the user etc.
JavaScript provides some built-in functions to display messages to the users using the browser window. These messages can be displayed via pop-up windows using alert(), prompt(), confirm(), console.log() and document.write() functions. These dialog boxes provide us with the ability to display in-formation, take input or to get any confirmation from the user. Using these functions, we can interact with the user. Each function has its own way of displaying the message to the user.
console.log()simply displays the message on the web browser's window. It is primarily used for debugging purposes.
Example: Try It
console.log(“Hello World via the console!”);
alert() is used to display a message on the web page. Using alert() triggers a pop-up window with the specified message. It provides a dialog box with a button that displays "ok". This is generally used to provide some warning or information to the user.
Example: Try It
alert("Hi Welcome to JavaScript Programming");
confirm() is the built-in function used to ask confirmation from the user. It displays the message and provides the user with two buttons, "ok" and "cancel".
Example: Try It
confirm("Do you want to close the page?");
prompt() dialog box is used to take input from the user. prompt() function displays two pieces of information; one is the message or label to be displayed in the dialog box, and the other is the default JavaScript string to be displayed. It also provides the user with two buttons, ok and cancel. If the user types in some value and selects ok, then the value is returned to the code. If the user selects cancel, then the function returns null to the calling code.
Example: Try It
name = prompt("Enter Your Name!"); alert("Hello! " + name);
document.write() is used whenever we want to print the content onto the HTML page. It is a simple, easy-to-use method for displaying content on to a web page.
Example: Try It
document.write("Welcome to the JavaScript Programming!"); document.write("<h2(">Welcome to the JavaScript Programming!("</h2">");
Math.random() command is used to create a random number.
Example: Try It
console.log(Math.random()); // outputs a decimal between 0 and 1.
If we want a number between 0 and 100, we can multiply it by 100, like this:
Example: Try It
console.log(Math.random() * 100);
If we don't want to have a decimal result, we can use the Math.round function on it, which is rounding it down to the nearest integer:
Example: Try It
console.log(Math.round(Math.random() * 100)); // Math.round method returns returns the value of a number rounded to the nearest integer. console.log(Math.floor(Math.random() * 100)); // Math.floor method returns the largest integer less than or equal to a number.
eval(string) Evaluate the string expression. If it’s a number, return the number.
Example: Try It
number = eval("3");